package com.uzai.console.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.EmojiUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.TbUserInfo.TbUserInfoIdDto;
import com.uzai.console.dto.TbUserInfo.TbUserInfoQuery;
import com.uzai.console.dto.TbUserInfo.TbUserInfoUpdateDto;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.groupsendjob.GroupSendChildidPushDto;
import com.uzai.console.dto.feign.groupsendjob.NewGroupSendMsgDto;
import com.uzai.console.dto.feign.userextinfo.AlipayUserAuthDto;
import com.uzai.console.dto.feign.userextinfo.UserExtInfoQueryDto;
import com.uzai.console.dto.feign.uzaimanage.SysRunlogWarningDto;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.user.UserUpdateMarketingTagDto;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.dto.user.wechatuser.PriRewardRulesDto;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.dto.user.wxworkuser.*;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsUserExtInfo;
import com.uzai.console.entity.es.EsWorkWxContacts;
import com.uzai.console.entity.es.WechatBlacklistPrv;
import com.uzai.console.entity.es.WechatBlacklistPub;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.enums.WxworkFriendRequestScene;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.*;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.tbuserinfo.TbUserInfoVo;
import com.uzai.console.vo.user.MarketingRewardVo;
import com.uzai.console.vo.user.SysTagShow;
import com.uzai.console.vo.user.SysTagVo;
import com.uzai.console.vo.user.UserTreeVo;
import com.uzai.console.vo.user.useraccdetail.UserAccDetailInfoVo;
import com.uzai.console.vo.user.wxworkuser.WxworkMinMaxCreateTimeVo;
import com.uzai.console.vo.user.wxworkuser.WxworkUserInfoVo;
import com.uzai.console.vo.user.wxworkuser.WxworkUserPageVo;
import com.uzai.console.vo.user.wxworkuser.WxworkUserSimpleVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业微信会员
 *
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class WxworkUserServiceImpl extends CommonService implements WxworkUserService {

    private Logger logger = LoggerFactory.getLogger(WxworkUserServiceImpl.class);

    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserOperatorService userOperatorService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private UserExtInfoFeignService userExtInfoFeignService;
    @Autowired
    private WxworkUserTreeInfoService wxworkUserTreeInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private PyqExpressionMapper pyqExpressionMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private UzaiCashierServerFeignService uzaiCashierServerFeignService;
    @Autowired
    private TakeBalBlacklistMapper takeBalBlacklistMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private MarketingRewardsService marketingRewardsService;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private MarketingTagMapper marketingTagMapper;
    @Autowired
    private UzaiManageFeignService uzaiManageFeignService;
    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private RiskLevelMapper riskLevelMapper;

    /**
     * 分页查询企业微信用户列表
     *
     * @param wxworkUserQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<WxworkUserPageVo> findWxworkUserList(WxworkUserQuery wxworkUserQuery) {

        logger.info("---wxworkUserQuery={}", JSONObject.toJSONString(wxworkUserQuery));

        //返回到页面分页对象
        Page<WxworkUserPageVo> pageVo = new Page<>();

        //新建返回到页面的LIST对象
        List<WxworkUserPageVo> wxworkUserPageVoList = new ArrayList<>();

        //判断是否需要脱敏
        Boolean tuominFlag_mobile = true;
        String cmstype_user_mobile_verified = (String) redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_USER_MOBILE, wxworkUserQuery.getMerId()));
        if (org.apache.commons.lang3.StringUtils.isNotBlank(cmstype_user_mobile_verified)) {
            tuominFlag_mobile = false;
        }


        //执行分页查询对象
        Page<WxworkUser> page = new Page<>();
        wxworkUserQuery.convert(page);

        //判断是否有淘宝会员id条件
        if (StringUtils.isNotBlank(wxworkUserQuery.getSpecialId())) {
            //清空其他条件
            WxworkUserQuery wxworkUserQuery_specialId = new WxworkUserQuery();
            wxworkUserQuery_specialId.setMerId(wxworkUserQuery.getMerId());
            wxworkUserQuery_specialId.setSize(wxworkUserQuery.getSize());
            wxworkUserQuery_specialId.setCurrent(wxworkUserQuery.getCurrent());
            wxworkUserQuery_specialId.setOrder(wxworkUserQuery.getOrder());
            wxworkUserQuery_specialId.setAsc(wxworkUserQuery.isAsc());
            wxworkUserQuery_specialId.setOrderByField(wxworkUserQuery.getOrderByField());
            wxworkUserQuery_specialId.setOrderItemList(wxworkUserQuery.getOrderItemList());
            wxworkUserQuery_specialId.setSpecialId(wxworkUserQuery.getSpecialId());
            //重新生成查询条件
            wxworkUserQuery = wxworkUserQuery_specialId;

            //查询淘宝会员信息
            TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
            tbUserInfoQuery.setMerId(wxworkUserQuery.getMerId());
            tbUserInfoQuery.setSpecialId(wxworkUserQuery.getSpecialId());
            List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(tbUserInfoQuery);
            if (tbUserInfoList != null && tbUserInfoList.size() > 0) {
                List<Long> userIdList = new ArrayList<>();
                for (TbUserInfo tbUserInfo : tbUserInfoList) {
                    userIdList.add(tbUserInfo.getUserId());
                }
                wxworkUserQuery.setIdList(userIdList);
            } else {//未查询到淘宝会员id,则返回空
                return pageVo;
            }
        }

        // 判断是否带有风险条件id
        if (wxworkUserQuery.getRiskLevelId() != null) {
            RiskLevel riskLevel = riskLevelMapper.selectById(wxworkUserQuery.getRiskLevelId());
            if (riskLevel != null) {
                wxworkUserQuery.setMaxScore(riskLevel.getMaxScore());
                wxworkUserQuery.setMinScore(riskLevel.getMinScore());
            }
        }

        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);


        if (wxworkUserList != null) {

            for (WxworkUser wxworkUser : wxworkUserList) {
                WxworkUserPageVo wxworkUserPageVo = new WxworkUserPageVo();
                BeanUtils.copyProperties(wxworkUser, wxworkUserPageVo);

                 // 查询风险等级
//                if (wxworkUser.getRiskScore() != null) {
//                    RiskLevel riskLevel = riskLevelMapper.selectByScore(wxworkUser.getRiskScore());
//                    if (riskLevel != null) {
//                        wxworkUserPageVo.setRiskLevelName(riskLevel.getName());
//                    }
//
//                }

                //处理淘礼金脱敏显示
                //是否脱敏处理
                if (tuominFlag_mobile) {
                    wxworkUserPageVo.setMobile(DesensitizeUtil.around(wxworkUserPageVo.getMobile(), 3, 4));
                }

                try {
                    //身份名称
                    wxworkUserPageVo.setIdentityName(IdentityEnum.getById(wxworkUserPageVo.getIdentity()).getDesc());

                    //会员类型名称
                    if (wxworkUserPageVo.getUserType() != null) {
                        UserType userType = userTypeMapper.selectById(wxworkUserPageVo.getUserType(), wxworkUserQuery.getMerId());
                        if (userType != null) {
                            wxworkUserPageVo.setUserTypeName(userType.getName());
                        }
                    }

                    //上级用户
                    if (wxworkUserPageVo.getParentId() != null) {
                        if (wxworkUserPageVo.getParentId().longValue() != 0) {
                            WxworkUser wxworkUserParent = wxworkUserMapper.selectById(wxworkUserPageVo.getParentId(), wxworkUserQuery.getMerId());
                            if (wxworkUserParent != null) {
                                wxworkUserPageVo.setParentName(wxworkUserParent.getNickName());
                            }
                        } else {
                            wxworkUserPageVo.setParentId(null);
                        }
                    }

                    //代理
                    if (wxworkUserPageVo.getAgentId() != null) {
                        if (wxworkUserPageVo.getAgentId().longValue() != 0) {
                            WxworkUser wxworkUserAgent = wxworkUserMapper.selectById(wxworkUserPageVo.getAgentId(), wxworkUserQuery.getMerId());
                            if (wxworkUserAgent != null) {
                                wxworkUserPageVo.setAgentName(wxworkUserAgent.getNickName());
                            }
                        } else {
                            wxworkUserPageVo.setAgentId(null);
                        }
                    }

                    //合伙人
                    if (wxworkUserPageVo.getPartnerId() != null) {
                        if (wxworkUserPageVo.getPartnerId().longValue() != 0) {
                            WxworkUser wxworkUserPartner = wxworkUserMapper.selectById(wxworkUserPageVo.getPartnerId(), wxworkUserQuery.getMerId());
                            if (wxworkUserPartner != null) {
                                wxworkUserPageVo.setPartnerName(wxworkUserPartner.getNickName());
                            }
                        } else {
                            wxworkUserPageVo.setPartnerId(null);
                        }
                    }

                    //查询机器人ID
                    if (wxworkUserPageVo.getDeviceUniqueId() != null) {
                        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUserPageVo.getDeviceUniqueId(), wxworkUserQuery.getMerId());
                        if (deviceWxworkInfo != null) {
                            wxworkUserPageVo.setDeviceId(deviceWxworkInfo.getDeviceId());
                            wxworkUserPageVo.setDeviceName(deviceWxworkInfo.getDeviceName());
                            wxworkUserPageVo.setDeviceRemark(deviceWxworkInfo.getDeviceRemark());
                        }
                    }

                    //用户类型组信息
                    if (wxworkUserPageVo.getUserType() != null) {
                        UserType userType = userTypeMapper.selectById(wxworkUserPageVo.getUserType(), wxworkUserQuery.getMerId());
                        if (userType != null) {
                            Long userTypeGroupId = userType.getGroupId();
                            if (userTypeGroupId != null) {
                                UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, wxworkUserQuery.getMerId());
                                if (userTypeGroup != null) {
                                    wxworkUserPageVo.setUserTypeGroupId(userTypeGroup.getId());
                                    wxworkUserPageVo.setUserTypeGroupName(userTypeGroup.getName());
                                }
                            }
                        }
                    }

                    //注册来源名称
                    if (wxworkUserPageVo.getRegChannel() != null) {
                        WxworkFriendRequestScene wxworkFriendRequestScene = WxworkFriendRequestScene.getById(wxworkUserPageVo.getRegChannel());
                        if (wxworkFriendRequestScene != null) {
                            wxworkUserPageVo.setRegChannelName(wxworkFriendRequestScene.getLabel());
                        }
                    }

                    //标签List
                    try {
                        wxworkUserPageVo.setTagsArr(JSONObject.parseArray(wxworkUserPageVo.getTags(), String.class));
                    } catch (Exception e) { //如果不是JSON格式

                    }

                    //会员标签
                    if (StringUtils.isNotBlank(wxworkUser.getSysTags())) {
                        try {
                            List<SysTagVo> sysTagVoList = JSONObject.parseArray(wxworkUser.getSysTags(), SysTagVo.class);

                            if (sysTagVoList != null && sysTagVoList.size() > 0) {
                                List<SysTagShow> sysTagShowList = new ArrayList<>();
                                List<Long> sysTagsArr = new ArrayList<>();
                                for (SysTagVo sysTagVo : sysTagVoList) {
                                    sysTagsArr.add(sysTagVo.getId());
                                    SysTagShow sysTagShow = new SysTagShow();
                                    BeanUtils.copyProperties(sysTagVo, sysTagShow);
                                    //查询标签名称
                                    MarketingTag marketingTag = marketingTagMapper.selectById(sysTagVo.getId(), wxworkUserQuery.getMerId());
                                    if (marketingTag != null) {
                                        sysTagShow.setName(marketingTag.getName());
                                    }
                                    sysTagShowList.add(sysTagShow);
                                }
                                wxworkUserPageVo.setSysTagsArr(sysTagsArr);
                                wxworkUserPageVo.setSysTagVoArr(sysTagShowList);
                            }
                        } catch (Exception e) { //如果不是JSON格式

                        }
                    }

                    //查询用户额外信息
                    UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                    userExtInfoQueryDto.setMerId(wxworkUserQuery.getMerId());
                    userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getId()); //企业微信会员
                    userExtInfoQueryDto.setBizUserId(wxworkUser.getBizUserId());
                    List<String> keys = new ArrayList<>();
                    keys.add("ValidOrderCount"); //首字母大写
                    userExtInfoQueryDto.setKeys(keys);

                    StopWatch stopWatch = new StopWatch();
                    stopWatch.start();

                    UzaiRespVo<EsUserExtInfo> uzaiRespVo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                    //logger.info("----订单总量----uzaiRespVo="+JSONObject.toJSONString(uzaiRespVo));

                    stopWatch.stop();
                    //logger.info("-获取订单总量接口分析：" + stopWatch.prettyPrint());

                    //超过10秒的事务，报警
                    if (stopWatch.getTotalTimeSeconds() > 10) {
                        SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                        sysRunlogWarningDto.setText("获取订单总量接口分析，超过10秒的请求监控！\n类名：WxworkUserServiceImpl" + "\n方法：findWxworkUserList" + "\n接口：getUserextinfo");
                        UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                        logger.info("--调用官方钉钉报警超过10秒未处理完成的获取订单总量接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                    }

                    if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                        EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                        if (esUserExtInfo != null) {
                            wxworkUserPageVo.setOrderCount(esUserExtInfo.getValidOrderCount());
                        }
                    }

                    //是否在白名单当中
                    String id_white = wxworkUserQuery.getMerId() + "_" + wxworkUser.getBizUserId();
                    Map<String, Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                    if (white_map != null) {
                        wxworkUserPageVo.setBlacklistFlag(3); //白名单
                        wxworkUserPageVo.setBlacklistId(wxworkUser.getBizUserId());
                    }

                    //是否在全网黑名单当中
                    String id_blacklistPub = wxworkUser.getBizUserId();
                    Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                    if (pub_map != null) {
                        wxworkUserPageVo.setBlacklistFlag(2); //共享全网黑名单
                        wxworkUserPageVo.setBlacklistId(wxworkUser.getBizUserId());
                    }

                    String id_blacklistPrv = wxworkUserQuery.getMerId() + "_" + wxworkUser.getBizUserId();
                    Map<String, Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                    if (prv_map != null) { //在私有黑名单当中
                        wxworkUserPageVo.setBlacklistFlag(1); //私有黑名单
                        wxworkUserPageVo.setBlacklistId(id_blacklistPrv);
                    }
                } catch (Exception e) {

                }
                wxworkUserPageVoList.add(wxworkUserPageVo);
            }
        }

        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wxworkUserPageVoList);
        //将返回对象排序(如果没有，则默认id排序降序)
        if (StringUtils.isBlank(wxworkUserQuery.getOrderByField()) && (wxworkUserQuery.getOrderItemList() == null || wxworkUserQuery.getOrderItemList().size() == 0)) {
            Tools.sort(wxworkUserPageVoList, "id", wxworkUserQuery.isAsc() ? "asc" : "desc");
        }

        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询下级用户列表
     *
     * @param wxworkFindSonUserListQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<WxworkUserPageVo> findSonUserList(WxworkFindSonUserListQuery wxworkFindSonUserListQuery) {
        Long parentId = wxworkFindSonUserListQuery.getParentId();
        if (parentId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入上级会员id");
        }

        Long merId = wxworkFindSonUserListQuery.getMerId();
        if (merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Integer type = Tools.getInteger(wxworkFindSonUserListQuery.getType());

        WxworkUser wxworkUser = wxworkUserMapper.selectById(parentId, merId);
        if (wxworkUser != null) {
            if (Tools.getInteger(wxworkUser.getIdentity()).intValue() == IdentityEnum.BUYER.getId().intValue()) { //此会员是买家，则通过parentId来查询
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                BeanUtils.copyProperties(wxworkFindSonUserListQuery, wxworkUserQuery);
                wxworkUserQuery.setMerId(wxworkFindSonUserListQuery.getMerId());
                wxworkUserQuery.setParentId(wxworkFindSonUserListQuery.getParentId());
                wxworkUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                return findWxworkUserList(wxworkUserQuery);
            } else if (Tools.getInteger(wxworkUser.getIdentity()).intValue() == IdentityEnum.AGENT.getId().intValue()) {
                if (type == 2) { //下级代理
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    BeanUtils.copyProperties(wxworkFindSonUserListQuery, wxworkUserQuery);
                    wxworkUserQuery.setParentId(null);
                    wxworkUserQuery.setMerId(wxworkFindSonUserListQuery.getMerId());
                    wxworkUserQuery.setAgentId(wxworkFindSonUserListQuery.getParentId());
                    wxworkUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    return findWxworkUserList(wxworkUserQuery);
                } else if (type == 3 || type == 4) { //直推或者非直推买家
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    BeanUtils.copyProperties(wxworkFindSonUserListQuery, wxworkUserQuery);
                    wxworkUserQuery.setParentId(null);
                    wxworkUserQuery.setMerId(wxworkFindSonUserListQuery.getMerId());
                    wxworkUserQuery.setAgentId(wxworkFindSonUserListQuery.getParentId());
                    wxworkUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    if (type == 3) { //直推
                        wxworkUserQuery.setBuyerType(1);
                    } else {
                        wxworkUserQuery.setBuyerType(2); //非直推
                    }
                    return findWxworkUserList(wxworkUserQuery);
                }
            } else { //合伙人
                if (type == 1) { //买家
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    BeanUtils.copyProperties(wxworkFindSonUserListQuery, wxworkUserQuery);
                    wxworkUserQuery.setParentId(null);
                    wxworkUserQuery.setMerId(wxworkFindSonUserListQuery.getMerId());
                    wxworkUserQuery.setPartnerId(wxworkFindSonUserListQuery.getParentId());
                    wxworkUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    return findWxworkUserList(wxworkUserQuery);
                } else if (type == 2) { //代理
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    BeanUtils.copyProperties(wxworkFindSonUserListQuery, wxworkUserQuery);
                    wxworkUserQuery.setParentId(null);
                    wxworkUserQuery.setMerId(wxworkFindSonUserListQuery.getMerId());
                    wxworkUserQuery.setPartnerId(wxworkFindSonUserListQuery.getParentId());
                    wxworkUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    return findWxworkUserList(wxworkUserQuery);
                }
            }
        }

        //返回到页面分页对象
        Page<WxworkUserPageVo> pageVo = new Page<>();
        BeanUtils.copyProperties(wxworkFindSonUserListQuery, pageVo);
        return pageVo;
    }


    /**
     * 查询企业微信用户详情
     *
     * @param wxworkUserIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public WxworkUserInfoVo findWxworkUserInfo(@RequestBody WxworkUserIdDto wxworkUserIdDto) {

        if (wxworkUserIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //查询页面用户
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserIdDto.getId(), wxworkUserIdDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //返回给页面参数
        WxworkUserInfoVo wxworkUserInfoVo = new WxworkUserInfoVo();
        BeanUtils.copyProperties(wxworkUser, wxworkUserInfoVo);

        // 查询撸狗风险值
//        if (wxworkUser.getRiskScore() != null) {
//            RiskLevel riskLevel = riskLevelMapper.selectByScore(wxworkUser.getRiskScore());
//            if (riskLevel != null) {
//                wxworkUserInfoVo.setRiskLevelName(riskLevel.getName());
//            }
//        }

        //判断是否需要脱敏,默认脱敏
        Boolean tuominFlag_wxid = true;
        String CMSTYPE_WECHATUSER_WXID_VERIFIED =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_WECHATUSER_WXID_VERIFIED, wxworkUserIdDto.getMerId(), wxworkUserInfoVo.getId()));
        if(StringUtils.isNotBlank(CMSTYPE_WECHATUSER_WXID_VERIFIED)){
            tuominFlag_wxid = false;
        }
        //是否脱敏处理
        if(tuominFlag_wxid){
            wxworkUserInfoVo.setWxid("");
        }else{
            wxworkUserInfoVo.setWxid(wxworkUser.getWxid());
        }

        //查询机器人ID
        if (wxworkUser.getDeviceUniqueId() != null) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUser.getDeviceUniqueId(), wxworkUser.getMerId());
            if (deviceWxworkInfo != null) {
                wxworkUserInfoVo.setDeviceId(deviceWxworkInfo.getDeviceId());
                wxworkUserInfoVo.setDeviceName(deviceWxworkInfo.getDeviceName());
                wxworkUserInfoVo.setDeviceRemark(deviceWxworkInfo.getDeviceRemark());
            }
        }

        //用户类型组信息
        if (wxworkUser.getUserType() != null) {
            UserType userType = userTypeMapper.selectById(wxworkUser.getUserType(), wxworkUserIdDto.getMerId());
            if (userType != null) {
                Long userTypeGroupId = userType.getGroupId();
                if (userTypeGroupId != null) {
                    UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, wxworkUserIdDto.getMerId());
                    if (userTypeGroup != null) {
                        wxworkUserInfoVo.setUserTypeGroupId(userTypeGroup.getId());
                        wxworkUserInfoVo.setUserTypeGroupName(userTypeGroup.getName());
                    }
                }
            }
        }

        //注册来源名称
        if (wxworkUserInfoVo.getRegChannel() != null) {
            WxworkFriendRequestScene wxworkFriendRequestScene = WxworkFriendRequestScene.getById(wxworkUserInfoVo.getRegChannel());
            if (wxworkFriendRequestScene != null) {
                wxworkUserInfoVo.setRegChannelName(wxworkFriendRequestScene.getLabel());
            }
        }


        //标签
        try {
            wxworkUserInfoVo.setTagsArr(JSONObject.parseArray(wxworkUser.getTags(), String.class));
        } catch (Exception e) { //如果不是JSON格式
        }

        //会员标签
        if (StringUtils.isNotBlank(wxworkUser.getSysTags())) {
            try {
                List<SysTagVo> sysTagVoList = JSONObject.parseArray(wxworkUser.getSysTags(), SysTagVo.class);
                if (sysTagVoList != null && sysTagVoList.size() > 0) {
                    List<SysTagShow> sysTagShowList = new ArrayList<>();
                    List<Long> sysTagsArr = new ArrayList<>();
                    for (SysTagVo sysTagVo : sysTagVoList) {
                        sysTagsArr.add(sysTagVo.getId());
                        SysTagShow sysTagShow = new SysTagShow();
                        BeanUtils.copyProperties(sysTagVo, sysTagShow);
                        //查询标签名称
                        MarketingTag marketingTag = marketingTagMapper.selectById(sysTagVo.getId(), wxworkUserIdDto.getMerId());
                        if (marketingTag != null) {
                            sysTagShow.setName(marketingTag.getName());
                        }
                        sysTagShowList.add(sysTagShow);
                    }
                    wxworkUserInfoVo.setSysTagsArr(sysTagsArr);
                    wxworkUserInfoVo.setSysTagVoArr(sysTagShowList);
                }
            } catch (Exception e) { //如果不是JSON格式

            }
        }


        //上级、代理、合伙人如果为0，变成null
        if (wxworkUserInfoVo.getParentId() != null && wxworkUserInfoVo.getParentId().longValue() == 0) {
            wxworkUserInfoVo.setParentId(null);
        }
        if (wxworkUserInfoVo.getAgentId() != null && wxworkUserInfoVo.getAgentId().longValue() == 0) {
            wxworkUserInfoVo.setAgentId(null);
        }
        if (wxworkUserInfoVo.getPartnerId() != null && wxworkUserInfoVo.getPartnerId().longValue() == 0) {
            wxworkUserInfoVo.setPartnerId(null);
        }

        //上级买家树
        if (StringUtils.isNotBlank(wxworkUserInfoVo.getParentInfo())) {
            String parentInfo = wxworkUserInfoVo.getParentInfo();
            if (parentInfo.length() > 19) {
                //需要判断此买家树是否包含下划线
                if (parentInfo.contains("_")) {
                    String[] parentIdList = wxworkUserInfoVo.getParentInfo().split("_");
                    if (parentIdList != null && parentIdList.length > 0) {
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList) {
                            UserTreeVo userTreeVo = new UserTreeVo();
                            WxworkUser wxworkUser_parent = wxworkUserMapper.selectById(Long.valueOf(parentId), wxworkUserIdDto.getMerId());
                            if (wxworkUser_parent != null) {
                                userTreeVo.setId(wxworkUser_parent.getId());
                                userTreeVo.setNickName(wxworkUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        wxworkUserInfoVo.setParentInfoList(parentInfoList);
                    }
                } else { //不包含下划线,根据id位数类截取，另外需要手动来修正买家树
                    String[] parentIdList = Tools.stringToStringArray(parentInfo, 19);
                    if (parentIdList != null && parentIdList.length > 0) {
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList) {
                            UserTreeVo userTreeVo = new UserTreeVo();
                            WxworkUser wxworkUser_parent = wxworkUserMapper.selectById(Long.valueOf(parentId), wxworkUserIdDto.getMerId());
                            if (wxworkUser_parent != null) {
                                userTreeVo.setId(wxworkUser_parent.getId());
                                userTreeVo.setNickName(wxworkUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        wxworkUserInfoVo.setParentInfoList(parentInfoList);

                        //手动修改买家树
                        String parentInfoNew = StringUtils.join(parentIdList, "_");
                        wxworkUser.setParentInfo(parentInfoNew);
                        wxworkUser.setUpdateTime(DateUtil.getNowTime());
                        wxworkUserMapper.updateParetInfo(wxworkUser);
                    }
                }
            } else {
                UserTreeVo userTreeVo = new UserTreeVo();
                WxworkUser wxworkUser_parent = wxworkUserMapper.selectById(Long.valueOf(parentInfo), wxworkUserIdDto.getMerId());
                if (wxworkUser_parent != null) {
                    List<UserTreeVo> parentInfoList = new ArrayList<>();
                    userTreeVo.setId(wxworkUser_parent.getId());
                    userTreeVo.setNickName(wxworkUser_parent.getNickName());
                    parentInfoList.add(userTreeVo);
                    wxworkUserInfoVo.setParentInfoList(parentInfoList);
                }
            }
        }

        //上级代理树
        if (StringUtils.isNotBlank(wxworkUserInfoVo.getAgentInfo())) {
            String[] agentIdList = wxworkUserInfoVo.getAgentInfo().split("_");
            if (agentIdList != null && agentIdList.length > 0) {
                List<UserTreeVo> agentInfoList = new ArrayList<>();
                for (String agentId : agentIdList) {
                    UserTreeVo userTreeVo = new UserTreeVo();
                    WxworkUser wxworkUser_agent = wxworkUserMapper.selectById(Long.valueOf(agentId), wxworkUserIdDto.getMerId());
                    if (wxworkUser_agent != null) {
                        userTreeVo.setId(wxworkUser_agent.getId());
                        userTreeVo.setNickName(wxworkUser_agent.getNickName());
                        agentInfoList.add(userTreeVo);
                    }
                }
                wxworkUserInfoVo.setAgentInfoList(agentInfoList);
            }
        }

        //是否在全网黑名单当中
        String id_blacklistPub = wxworkUser.getBizUserId();
        Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
        if (pub_map != null) {
            wxworkUserInfoVo.setBlacklistFlag(2); //共享全网黑名单
            wxworkUserInfoVo.setBlacklistId(wxworkUser.getBizUserId());
        }

        //是否在白名单当中
        String id_white = wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
        Map<String, Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
        if (white_map != null) {
            wxworkUserInfoVo.setBlacklistFlag(3); //白名单
            wxworkUserInfoVo.setBlacklistId(wxworkUser.getBizUserId());
        }

        String id_blacklistPrv = wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
        Map<String, Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
        if (prv_map != null) { //在私有黑名单当中
            wxworkUserInfoVo.setBlacklistFlag(1); //私有黑名单
            wxworkUserInfoVo.setBlacklistId(id_blacklistPrv);
        }

        //会员其他端互通信息
        if (StringUtils.isNotBlank(wxworkUser.getUzaiUnionId())) {
            //公众号互通
            WxpubUser wxpubUser = wxpubUserMapper.selectByUzaiUnionId(wxworkUser.getUzaiUnionId(), wxworkUser.getMerId());
            if (wxpubUser != null) {
                wxworkUserInfoVo.setWxpubUserId(wxpubUser.getId());
            }

            //个人微信互通
            WechatUser wechatUser = wechatUserMapper.selectByUzaiUnionId(wxworkUser.getUzaiUnionId(), wxworkUser.getMerId());
            if (wechatUser != null) {
                wxworkUserInfoVo.setWechatUserId(wechatUser.getId());
            }
        }

        //如果会员昵称和会员头像都为空，则从ES中更新下信息
        if (StringUtils.isBlank(wxworkUser.getNickName()) || StringUtils.isBlank(wxworkUser.getHeadImg())) {
            //从ES中获取个人微信信息
            if (wxworkUser.getDeviceUniqueId() != null) {
                DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUser.getDeviceUniqueId(), wxworkUserIdDto.getMerId());
                if (deviceWxworkInfo != null) {
                    if (StringUtils.isNotBlank(deviceWxworkInfo.getDeviceId())) {
                        String esId = wxworkUser.getMerId() + "_" + deviceWxworkInfo.getDeviceId() + "_" + wxworkUser.getBizUserId();
                        try {

                            //通过查询运营商其他索引分片获取分片索引
                            String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkUserIdDto.getMerId());
                            Map<String, Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_contacts, esId, null);
                            EsWorkWxContacts esWorkWxContacts = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), EsWorkWxContacts.class);
                            if (esWorkWxContacts != null) {
                                //更新微信信息
                                wxworkUser.setWxid(esWorkWxContacts.getWxid());
                                wxworkUser.setNickName(esWorkWxContacts.getUserName());
                                wxworkUser.setHeadImg(esWorkWxContacts.getHimg());
                                wxworkUser.setRemark(esWorkWxContacts.getRemark());
                                wxworkUserMapper.updateById(wxworkUser);

                                //返回ES中的数据到前端
                                wxworkUserInfoVo.setNickName(esWorkWxContacts.getUserName());
                                wxworkUserInfoVo.setHeadImg(esWorkWxContacts.getHimg());
                                wxworkUserInfoVo.setRemark(esWorkWxContacts.getRemark());
                            }
                        } catch (Exception e) {
                            logger.error("从ES中查询企业微信通讯录:error:" + e.getMessage());
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新企业微信信息失败");
                        }
                    }
                }
            }
        }

        try {
            //关联其他机器人
            List<DeviceInfoVo> deviceInfoVoList = new ArrayList<>();
            wxworkUserInfoVo.setDeviceInfoList(deviceInfoVoList);
            if (StringUtils.isNotBlank(wxworkUser.getDeviceInfos())) {
                List<Long> deviceInfoList = JSONObject.parseArray(wxworkUser.getDeviceInfos(), Long.class);
                if (deviceInfoList != null && deviceInfoList.size() > 0) {
                    for (Long deviceUniqueId : deviceInfoList) {
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, DeviceTypeEnum.DT_WORK_WECHAT.getKey(), wxworkUser.getMerId());
                        if (device != null) {
                            DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                            BeanUtils.copyProperties(device, deviceInfoVo);
                            deviceInfoVoList.add(deviceInfoVo);
                        }
                    }
                }
            }
        } catch (Exception e) {

        }

        try {
            //营销数据
            String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
            String marketingRewardId = wxworkUser.getId() + "" + wxworkUser.getRegSource();
            Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
            MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
            if (marketingRewardVo == null) {
                marketingRewardVo = new MarketingRewardVo(true);
            }
            wxworkUserInfoVo.setMarketingReward(marketingRewardVo);

            String marketingRewardsBlackListId = marketingRewardsBlackListService.isInBlackList(wxworkUser.getBizUserId(), wxworkUser.getMerId());
            wxworkUserInfoVo.setMarketingRewardsBlackListId(marketingRewardsBlackListId);
        } catch (Exception e) {

        }


        //淘宝SID,默认查询第一条
        TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
        tbUserInfoQuery.setMerId(wxworkUser.getMerId());
        tbUserInfoQuery.setUserId(wxworkUser.getId());
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(new Page<>(), tbUserInfoQuery);
        if (tbUserInfoList != null && tbUserInfoList.size() > 0) {
            wxworkUserInfoVo.setSpecialId(tbUserInfoList.get(0).getSpecialId());
        }

        return wxworkUserInfoVo;
    }

    /**
     * 根据单个机器人群发消息
     *
     * @param wxworkUserBatchSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Integer groupSendMsgByDeviceUniqueId(WxworkUserBatchSendMsgDto wxworkUserBatchSendMsgDto) {
        //记录失败发送总数
        int totalCount_son_succ = 0;

        //群发消息设置
        WxworkUserGroupSendMsgDto wxworkUserGroupSendMsgDto = wxworkUserBatchSendMsgDto.getWxworkUserGroupSendMsgDto();
        //查询会员条件
        WxworkUserQuery wxworkUserQuery = wxworkUserBatchSendMsgDto.getWxworkUserQuery();
        wxworkUserQuery.setMerId(wxworkUserBatchSendMsgDto.getMerId());
        if (wxworkUserQuery == null) {//判断条件是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; wxworkUserQuery is null");
            return totalCount_son_succ;
        }
        if (wxworkUserQuery.getDeviceUniqueId() == null) {//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return totalCount_son_succ;
        }

        //查询数据库当中主任务是否存在
        if (wxworkUserBatchSendMsgDto.getGroupSendJobParentId() == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParentId is null");
            return totalCount_son_succ;
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUserQuery.getDeviceUniqueId(), wxworkUserBatchSendMsgDto.getMerId());
        if (deviceWxworkInfo == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWxworkInfo is null,  deviceUniqueId={}" + wxworkUserQuery.getDeviceUniqueId());
            return totalCount_son_succ;
        }

        //免打扰时间
        Integer busyTimeInterval = wxworkUserGroupSendMsgDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if (busyTimeInterval != null) {
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = wxworkUserGroupSendMsgDto.getBeginTime() - busyTimeInterval * 3600;
            wxworkUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询这个机器人的所有会员-根据创建时间来分段查询
        //先查询创建时间最小得会员-然后根据10天内创建时间段来查询所有得会员
        WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
        //查询总数
        Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
        //有总数
        if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
            int now = DateUtil.getNowTime();
            //添加群发消息子任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(wxworkUserBatchSendMsgDto.getGroupSendJobParentId()); //主任务id
            groupSendJob_son.setMerId(wxworkUserBatchSendMsgDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wxworkUserQuery.getDeviceUniqueId());
            groupSendJob_son.setName(wxworkUserGroupSendMsgDto.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.WORK_USER.getId());
            groupSendJob_son.setContent(Tools.getStr(wxworkUserGroupSendMsgDto.getContent()));
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(0); //默认发送总数为0
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(wxworkUserGroupSendMsgDto.getTimeInterval());
            groupSendJob_son.setBeginTime(wxworkUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setExptime(now + 15 * 24 * 3600); //当前时间之后的15天内
            groupSendJob_son.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(wxworkUserGroupSendMsgDto.getUserLabList())));
            groupSendJob_son.setCleanLab(wxworkUserGroupSendMsgDto.getCleanLab());
            groupSendJob_son.setUserRemark(Tools.getStr(wxworkUserGroupSendMsgDto.getUserRemark()));
            groupSendJob_son.setNightTime(wxworkUserGroupSendMsgDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(wxworkUserGroupSendMsgDto.getBusyTimeInterval());
            groupSendJob_son.setSendStartTime(wxworkUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setIgnoreName(Tools.getStrEmpty(JSONObject.toJSONString(wxworkUserQuery.getNameExcludeList())));
            groupSendJob_son.setIgnoreRemark(Tools.getStrEmpty(JSONObject.toJSONString(wxworkUserQuery.getRemarkExcludeList())));
            groupSendJob_son.setParaQueryType(1); //先筛选条件在创建任务
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try {
                //延迟时间
                int delay = 0;//循环累加延迟时间
                //则循环查询5天内的创建的会员
                int duration = 10 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        //每个时间段分页查询，每页10个
                        Page<WxworkUserSimpleVo> page = new Page<>();
                        int current = 1;
                        page.setCurrent(current);
                        page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
                        List<WxworkUserSimpleVo> wxworkUserSimpleVoList = wxworkUserMapper.findSimpleByList(page, wxworkUserQuery);
                        while (wxworkUserSimpleVoList != null && wxworkUserSimpleVoList.size() > 0) {
                            List<NewGroupSendMsgDto> groupSendMsgDtoList = new ArrayList<>();
                            //发送消息
                            for (WxworkUserSimpleVo wxworkUserSimpleVo : wxworkUserSimpleVoList) {
                                //发送MQ消息
                                NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                                newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                                newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                                String msg = Tools.getStr(groupSendJob_son.getContent());
                                msg = msg.replace("[随机表情]", Tools.getStr(EmojiUtil.getRandomEmoji()))
                                        .replace("[昵称]", Tools.getStr(wxworkUserSimpleVo.getNickName()));
                                newGroupSendMsgDto.setMsg(msg);
                                newGroupSendMsgDto.setMerId(wxworkUserSimpleVo.getMerId());
                                newGroupSendMsgDto.setDeviceUniqueId(wxworkUserSimpleVo.getDeviceUniqueId());
                                newGroupSendMsgDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                                newGroupSendMsgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                                newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                                newGroupSendMsgDto.setUserId(wxworkUserSimpleVo.getId());
                                newGroupSendMsgDto.setBizUserId(wxworkUserSimpleVo.getBizUserId());
                                newGroupSendMsgDto.setNickName(wxworkUserSimpleVo.getNickName());
                                newGroupSendMsgDto.setDelay(delay);
                                newGroupSendMsgDto.setOriginalDelay(delay);
                                delay = delay + wxworkUserGroupSendMsgDto.getTimeInterval(); //循环累加延迟时间
                                newGroupSendMsgDto.setRetry(0);
                                newGroupSendMsgDto.setLabel(groupSendJob_son.getUserLab());
                                newGroupSendMsgDto.setCleanLab(groupSendJob_son.getCleanLab());
                                String remark = Tools.getStr(groupSendJob_son.getUserRemark());
                                remark = remark.replace("[昵称]", Tools.getStr(wxworkUserSimpleVo.getNickName()))
                                        .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                                newGroupSendMsgDto.setRemark(remark);
                                groupSendMsgDtoList.add(newGroupSendMsgDto);
                            }

                            //群发消息
                            if (groupSendMsgDtoList.size() > 0) {
                                UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                                if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                                    totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                    logger.info("----查询结果群发消息调用微服务推送消息---para={}, size={}, result={}", JSONObject.toJSONString(groupSendMsgDtoList), groupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                                } else {
                                    logger.error("---查询结果群发消息第二次调用微服务推送消息---error={}", uzaiRespVo.getMsg());
                                    //失败的在调用一次,再次失败则修改群发消息条数
                                    UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                                    if (uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                        logger.error("---查询结果群发消息第二次调用微服务推送消息成功---msg={}", uzaiRespVo_repeat.getMsg());
                                        totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                    } else {
                                        logger.error("---查询结果群发消息第二次调用微服务推送消息---error={}", uzaiRespVo_repeat.getMsg());
                                    }
                                }
                            }

                            //再次查询下一页
                            current++;
                            page.setCurrent(current);
                            wxworkUserSimpleVoList = wxworkUserMapper.findSimpleByList(page, wxworkUserQuery);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("---企业微微信会员群发消息异常---deviceUniqueId={},msg={}", wxworkUserQuery.getDeviceUniqueId(), e.getMessage());
            }

            //修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(totalCount_son_succ);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval());
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }

        return totalCount_son_succ;
    }

    /**
     * (多选框选择会员)根据单个机器人群发消息(异步)
     *
     * @param wxworkUserSendMsgBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Integer groupSendMsgByDeviceUniqueIdBatch(WxworkUserSendMsgBatchDto wxworkUserSendMsgBatchDto) {

        //记录失败发送总数
        int totalCount_son_succ = 0;

        //查询这个机器人的所有会员
        List<Long> idList = wxworkUserSendMsgBatchDto.getIdList();
        if (idList == null || idList.size() == 0) {
            logger.error("--groupSendMsgByDeviceUniqueIdBatch is error; idList is null");
            return totalCount_son_succ;
        }

        if (wxworkUserSendMsgBatchDto.getDeviceUniqueId() == null) {//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return totalCount_son_succ;
        }

        //查询数据库当中主任务是否存在
        if (wxworkUserSendMsgBatchDto.getGroupSendJobParentId() == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParentId is null");
            return totalCount_son_succ;
        }

        //获取群发消息任务内容
        WxworkUserGroupSendMsgDto wxworkUserGroupSendMsgDto = wxworkUserSendMsgBatchDto.getWxworkUserGroupSendMsgDto();
        wxworkUserGroupSendMsgDto.setMerId(wxworkUserSendMsgBatchDto.getMerId());
        if (wxworkUserGroupSendMsgDto == null) {
            return totalCount_son_succ;
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUserSendMsgBatchDto.getDeviceUniqueId(), wxworkUserSendMsgBatchDto.getMerId());
        if (deviceWxworkInfo == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWxworkInfo is null,  deviceUniqueId={}" + wxworkUserSendMsgBatchDto.getDeviceUniqueId());
            return totalCount_son_succ;
        }

        //封装该机器人下的会员
        List<WxworkUser> wxworkUserList = new ArrayList<>();
        if (idList != null && idList.size() > 0) {
            for (Long id : idList) {
                WxworkUser wxworkUser = wxworkUserMapper.selectById(id, wxworkUserSendMsgBatchDto.getMerId());
                if (wxworkUser.getDeviceUniqueId().longValue() == deviceWxworkInfo.getId().longValue()) { //匹配该机器人的用户
                    wxworkUserList.add(wxworkUser);
                }
            }
        }

        if (wxworkUserList != null && wxworkUserList.size() > 0) {
            Integer now = DateUtil.getNowTime();
            //添加群发消息子任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(wxworkUserSendMsgBatchDto.getGroupSendJobParentId()); //主任务id
            groupSendJob_son.setMerId(wxworkUserSendMsgBatchDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wxworkUserSendMsgBatchDto.getDeviceUniqueId());
            groupSendJob_son.setName(wxworkUserGroupSendMsgDto.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.WORK_USER.getId());
            groupSendJob_son.setContent(Tools.getStr(wxworkUserGroupSendMsgDto.getContent()));
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(0);  //默认发送数为0
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(wxworkUserGroupSendMsgDto.getTimeInterval());
            groupSendJob_son.setBeginTime(wxworkUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setExptime(now + 15 * 24 * 3600); //当前时间之后的15天内
            groupSendJob_son.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(wxworkUserGroupSendMsgDto.getUserLabList())));
            groupSendJob_son.setCleanLab(wxworkUserGroupSendMsgDto.getCleanLab());
            groupSendJob_son.setUserRemark(Tools.getStr(wxworkUserGroupSendMsgDto.getUserRemark()));
            groupSendJob_son.setNightTime(wxworkUserGroupSendMsgDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(wxworkUserGroupSendMsgDto.getBusyTimeInterval());
            groupSendJob_son.setSendStartTime(wxworkUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try {

                //延迟时间
                int delay = 0;//循环累加延迟时间
                //发送消息
                List<NewGroupSendMsgDto> groupSendMsgDtoList = new ArrayList<>();
                for (WxworkUser wxworkUser : wxworkUserList) {
                    if (wxworkUser != null) {
                        //发送MQ消息
                        NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                        newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                        newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                        String msg = Tools.getStr(groupSendJob_son.getContent());
                        msg = msg.replace("[随机表情]", Tools.getStr(EmojiUtil.getRandomEmoji()))
                                .replace("[昵称]", Tools.getStr(wxworkUser.getNickName()));
                        newGroupSendMsgDto.setMsg(msg);
                        newGroupSendMsgDto.setMerId(wxworkUser.getMerId());
                        newGroupSendMsgDto.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
                        newGroupSendMsgDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                        newGroupSendMsgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                        newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                        newGroupSendMsgDto.setUserId(wxworkUser.getId());
                        newGroupSendMsgDto.setBizUserId(wxworkUser.getBizUserId());
                        newGroupSendMsgDto.setNickName(wxworkUser.getNickName());
                        newGroupSendMsgDto.setDelay(delay);
                        newGroupSendMsgDto.setOriginalDelay(delay);
                        delay = delay + groupSendJob_son.getTimeInterval(); //循环累加延迟时间
                        newGroupSendMsgDto.setRetry(0);
                        newGroupSendMsgDto.setLabel(groupSendJob_son.getUserLab());
                        newGroupSendMsgDto.setCleanLab(groupSendJob_son.getCleanLab());
                        String remark = Tools.getStr(groupSendJob_son.getUserRemark());
                        remark = remark.replace("[昵称]", Tools.getStr(wxworkUser.getNickName()))
                                .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                        newGroupSendMsgDto.setRemark(remark);
                        groupSendMsgDtoList.add(newGroupSendMsgDto);
                    }

                    //大于10个消息就发送一次，发送成功就清空该列表
                    if (groupSendMsgDtoList != null && groupSendMsgDtoList.size() >= 10) {
                        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                        if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                            logger.info("----手动选择会员群发调用微服务推送消息成功---para={},result={}", JSONObject.toJSONString(groupSendMsgDtoList), JSONObject.toJSONString(uzaiRespVo));
                            totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                            //清空发送消息
                            groupSendMsgDtoList.clear();
                        } else {
                            logger.info("----手动选择会员群发第二次调用微服务推送消息---error={}", uzaiRespVo.getMsg());
                            //失败的在调用一次,再次失败则修改群发消息条数
                            UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                            if (uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                logger.info("----手动选择会员群发第二次调用微服务推送消息成功---msg={}", uzaiRespVo_repeat.getMsg());
                                totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                //清空发送消息
                                groupSendMsgDtoList.clear();
                            } else {
                                logger.error("----手动选择会员群发第二次调用微服务推送消息失败---error={}", uzaiRespVo_repeat.getMsg());
                            }
                        }
                    }
                }

                //最后在统一发送剩余的消息
                if (groupSendMsgDtoList != null && groupSendMsgDtoList.size() > 0) {
                    UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                    if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                        logger.info("----手动选择会员群发调用微服务推送消息成功---para={},result={}", JSONObject.toJSONString(groupSendMsgDtoList), JSONObject.toJSONString(uzaiRespVo));
                        totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                        //清空发送消息
                        groupSendMsgDtoList.clear();
                    } else {
                        logger.info("----手动选择会员群发第二次调用微服务推送消息---error={}", uzaiRespVo.getMsg());
                        //失败的在调用一次,再次失败则修改群发消息条数
                        UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                        if (uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                            logger.info("----手动选择会员群发第二次调用微服务推送成功---msg={}", uzaiRespVo_repeat.getMsg());
                            totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                            //清空发送消息
                            groupSendMsgDtoList.clear();
                        } else {
                            logger.error("----手动选择会员群发第二次调用微服务推送消息失败---error={}", uzaiRespVo_repeat.getMsg());
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("---企业微信会员群发消息异常---deviceUniqueId={},msg={}", wxworkUserSendMsgBatchDto.getDeviceUniqueId(), e.getMessage());
            }

            //修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(totalCount_son_succ);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval());
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));

        }

        return totalCount_son_succ;
    }

    /**
     * 删除用户信息
     *
     * @param id
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteUserById(Long id, Long merId) {
        WxworkUser wxworkUser = wxworkUserMapper.selectById(id, merId);
        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        //判断是否关联APP，如果关联，不允许删除
        int appUserCount = appUserMapper.countByRelUserId(wxworkUser.getId());
        if (appUserCount > 0) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "此会员关联app，不能删除");
        }

        int now = DateUtil.getNowTime();

        //真删除
        wxworkUserMapper.deleteById(id, merId);

        //删除缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.WXWORK_USER_ID.getKey(), merId, wxworkUser.getBizUserId()));

        //删除ES
        try {
            //删除会员基本信息
            String uzai_user_info_id = DeviceTypeEnum.DT_WORK_WECHAT.getKey() + "_" + wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
            String uzai_user_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_INFO, wxworkUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_info, uzai_user_info_id);

            //删除会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_WORK_WECHAT.getKey() + "_" + wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
            String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_ext_info, uzai_user_ext_info_id);

            //删除营销奖励信息
            String uzai_user_marketing_reward_info_id = wxworkUser.getId() + "" + wxworkUser.getRegSource();
            elasticsearchUtil.deleteDataById(EsIndexName.UZAI_MARKETING_REWARD_INFO, uzai_user_marketing_reward_info_id);

        } catch (Exception e) {
            logger.error("删除ES会员扩展信息出现异常:{}" + e.getMessage());
        }


        //根据此会员的身份来查询下级用户
        if (wxworkUser.getIdentity().intValue() == IdentityEnum.BUYER.getId()) { //此会员是买家
            //查询所有下级买家
            WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
            wxworkUserQuery.setMerId(wxworkUser.getMerId());
            wxworkUserQuery.setParentId(wxworkUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
            //查询总数
            Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
            //有总数，且最小创建时间有
            if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                        if (wxworkUserList != null && wxworkUserList.size() > 0) {
                            for (WxworkUser wxworkUser_son : wxworkUserList) {
                                //旧上级树
                                String parentInfoOld_Nson = wxworkUser_son.getParentInfo();
                                //将此会员的上级清空
                                wxworkUser_son.setParentId(0L);
                                wxworkUser_son.setParentInfo("");
                                wxworkUser_son.setUpdateTime(now);
                                wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                //批量替换清空
                                wxworkUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", wxworkUser_son.getMerId(), true);
                                wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, "", wxworkUser_son.getMerId(), false);
                            }
                        }
                    }
                }
            }
        } else if (wxworkUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//代理身份
            //查询所有下级代理
            WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
            wxworkUserQuery.setMerId(wxworkUser.getMerId());
            wxworkUserQuery.setAgentId(wxworkUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
            //查询总数
            Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
            //有总数，且最小创建时间有
            if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                        if (wxworkUserList != null && wxworkUserList.size() > 0) {
                            for (WxworkUser wxworkUser_son : wxworkUserList) {
                                //旧代理树
                                String agentInfoOld_Nson = wxworkUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                wxworkUser_son.setAgentId(0L);
                                wxworkUser_son.setAgentInfo("");
                                wxworkUser_son.setUpdateTime(now);
                                wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                //批量替换
                                wxworkUserMapper.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", wxworkUser_son.getMerId(), true);
                                wxworkUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, "", wxworkUser_son.getMerId(), false);

                            }
                        }
                    }
                }
            }
        } else if (wxworkUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//合伙人身份
            //查询所有下级代理
            WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
            wxworkUserQuery.setMerId(wxworkUser.getMerId());
            wxworkUserQuery.setPartnerId(wxworkUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
            //查询总数
            Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
            //有总数，且最小创建时间有
            if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                        if (wxworkUserList != null && wxworkUserList.size() > 0) {
                            for (WxworkUser wxworkUser_son : wxworkUserList) {
                                //清空合伙人
                                wxworkUser_son.setPartnerId(0L);
                                wxworkUser_son.setUpdateTime(now);
                                wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * 删除上下级会员关系
     *
     * @param wxworkUserDeleteSonDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteSonWxworkUser(WxworkUserDeleteSonDto wxworkUserDeleteSonDto) {

        Long merId = wxworkUserDeleteSonDto.getMerId();
        Long id = wxworkUserDeleteSonDto.getId();
        Integer identity = wxworkUserDeleteSonDto.getIdentity();

        if (identity == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入身份参数");
        }

        if (id == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入会员id");
        }

        WxworkUser wxworkUser = wxworkUserMapper.selectById(id, merId);
        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        //上级会员
        WxworkUser wxworkUserParent = null;

        //根据此会员的身份来查询下级用户
        if (identity.intValue() == IdentityEnum.BUYER.getId().intValue()) { //此会员是买家

            Long parentId = wxworkUser.getParentId();
            wxworkUserParent = wxworkUserMapper.selectById(parentId, merId);

            //清理上级买家关系
            wxworkUser.setParentId(0L);
            wxworkUser.setParentInfo("");
            wxworkUser.setUpdateTime(DateUtil.getNowTime());
            wxworkUserMapper.updateIdentityInfo(wxworkUser);

            //查询所有下级买家
            WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
            wxworkUserQuery.setMerId(wxworkUser.getMerId());
            wxworkUserQuery.setParentId(wxworkUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
            //查询总数
            Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
            //有总数，且最小创建时间有
            if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                        if (wxworkUserList != null && wxworkUserList.size() > 0) {
                            for (WxworkUser wxworkUser_son : wxworkUserList) {
                                //旧上级树
                                String parentInfoOld_Nson = wxworkUser_son.getParentInfo();
                                //将此会员的上级树修改为上级的id
                                wxworkUser_son.setParentInfo(String.valueOf(wxworkUser.getId()));
                                wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                //批量替换清空
                                wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, String.valueOf(wxworkUser.getId()), wxworkUser.getMerId(), false);
                            }
                        }
                    }
                }
            }
        } else if (identity.intValue() == IdentityEnum.AGENT.getId().intValue()) {//代理身份

            Long agentId = wxworkUser.getAgentId();
            wxworkUserParent = wxworkUserMapper.selectById(agentId, merId);

            //清理上级代理关系
            wxworkUser.setAgentId(0L);
            wxworkUser.setAgentInfo("");
            wxworkUser.setUpdateTime(DateUtil.getNowTime());
            wxworkUserMapper.updateIdentityInfo(wxworkUser);

            //查询所有下级代理
            WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
            wxworkUserQuery.setMerId(wxworkUser.getMerId());
            wxworkUserQuery.setAgentId(wxworkUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
            //查询总数
            Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
            //有总数，且最小创建时间有
            if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                        if (wxworkUserList != null && wxworkUserList.size() > 0) {
                            for (WxworkUser wxworkUser_son : wxworkUserList) {
                                //旧代理树
                                String agentInfoOld_Nson = wxworkUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                wxworkUser_son.setAgentInfo(String.valueOf(wxworkUser.getId()));
                                wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                //批量替换
                                wxworkUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, String.valueOf(wxworkUser.getId()), wxworkUser.getMerId(), false);
                            }
                        }
                    }
                }
            }
        } else if (identity.intValue() == IdentityEnum.PARTNER.getId().intValue()) { //合伙人

            Long partnerId = wxworkUser.getPartnerId();
            wxworkUserParent = wxworkUserMapper.selectById(partnerId, merId);

            //清理合伙人关系
            wxworkUser.setPartnerId(0L);
            wxworkUser.setUpdateTime(DateUtil.getNowTime());
            wxworkUserMapper.updateIdentityInfo(wxworkUser);
        }

        //修改ES缓存
        //修改ES
        try {
            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_WORK_WECHAT.getKey() + "_" + wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
            //查询会员基本信息
            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId()), uzai_user_ext_info_id, null);
            if (dataMp_ext != null) {
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(wxworkUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId()), uzai_user_ext_info_id);
            }
        } catch (Exception e) {
            logger.error("修改会员营销策略信息出现异常:{}" + e.getMessage());
        }

        //断绝下级关系，发送修改会员敏感信息报警消息
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(wxworkUserDeleteSonDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER.getValue()); //修改会员敏感信息
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, wxworkUserDeleteSonDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);

        //发送修改会员数据提醒通知
        if (wxworkUserParent == null) {
            wxworkUserParent = new WxworkUser();
        }
        StringBuffer content = new StringBuffer("正在删除会员的下级：")
                .append(wxworkUser.getNickName())
                .append("(").append(wxworkUser.getWxid()).append(")");

        ext.put("childuser", loginVo.getLoginName());
        ext.put("content", content);
        ext.put("nick", wxworkUserParent.getNickName());
        ext.put("wxid", wxworkUserParent.getBizUserId());
        ext.put("userid", wxworkUserParent.getId());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送删除下级会员关系报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
    }

    /**
     * 分页查询企业微信用户账户明细列表
     *
     * @param userAccDetailQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<UserAccDetailInfoVo> findWxworkUserAccDetailList(UserAccDetailQuery userAccDetailQuery) {

        //用户ID不能为空，必须指定用户
        if (userAccDetailQuery.getUserId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请指定用户进行查询");
        }

        //新建返回到页面的LIST对象
        List<UserAccDetailInfoVo> wxworkUserAccDetailInfoVoList = new ArrayList<UserAccDetailInfoVo>();
        //执行分页查询对象
        Page<UserAccDetail> page = new Page<>();
        userAccDetailQuery.convert(page);
        List<UserAccDetail> userAccDetailList = null;
        if (super.checkStartEndTimeIsHistoryQuery(userAccDetailQuery.getQueryStartTime(), userAccDetailQuery.getQueryEndTime(), userAccDetailQuery.getQueryMonth())) {
            String tableSuffix = DateTime.of(userAccDetailQuery.getQueryEndTime() * 1000L).toString("yyMM");
            UzaiRespVo<Page<UserAccDetail>> listUzaiRespVoRes = historyDataFeignService.searchAccDetail(tableSuffix, userAccDetailQuery);
            if (listUzaiRespVoRes.getCode() != 200) {
                throw new BusinessException("提现列表查询失败");
            }

            if (listUzaiRespVoRes.getData() != null) {
                userAccDetailList = listUzaiRespVoRes.getData().getRecords();
                page.setTotal(listUzaiRespVoRes.getData().getTotal());
            }

        } else {// 反之查询90天内的订单数据
            userAccDetailList = userAccDetailMapper.findByList(page, userAccDetailQuery);
        }

        if (userAccDetailList != null) {
            for (UserAccDetail wxworkUserAccDetail : userAccDetailList) {
                UserAccDetailInfoVo wxworkUserAccDetailInfoVo = new UserAccDetailInfoVo();
                BeanUtils.copyProperties(wxworkUserAccDetail, wxworkUserAccDetailInfoVo);
                //用户昵称
                WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserAccDetail.getUserId(), userAccDetailQuery.getMerId());
                if (wxworkUser != null) {
                    wxworkUserAccDetailInfoVo.setNickName(wxworkUser.getNickName());
                }
                //明细类型
                wxworkUserAccDetailInfoVo.setTypeName(AccDetailTypeEnum.getById(wxworkUserAccDetail.getType()).getDesc());

                //订单编号商户订单号
                wxworkUserAccDetailInfoVo.setOrderIdTradeno(Tools.getStr(wxworkUserAccDetail.getOrderId()) + "/" + Tools.getStr(wxworkUserAccDetail.getTradeno()));
                wxworkUserAccDetailInfoVoList.add(wxworkUserAccDetailInfoVo);
            }
        }
        //返回到页面分页对象
        Page<UserAccDetailInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wxworkUserAccDetailInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询用户会员渠道ID列表
     *
     * @param tbUserInfoQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<TbUserInfoVo> findTbUserInfoList(TbUserInfoQuery tbUserInfoQuery) {
        //新建返回到页面的LIST对象
        List<TbUserInfoVo> tbUserInfoVoList = new ArrayList<TbUserInfoVo>();
        //执行分页查询对象
        Page<TbUserInfo> page = new Page<>();
        tbUserInfoQuery.convert(page);
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(page, tbUserInfoQuery);
        if (tbUserInfoList != null) {
            for (TbUserInfo tbUserInfo : tbUserInfoList) {
                TbUserInfoVo tbUserInfoVo = new TbUserInfoVo();
                BeanUtils.copyProperties(tbUserInfo, tbUserInfoVo);
                //用户昵称
                TbToken tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(), 0);
                if (tbToken == null) {
                    tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(), 1);
                }
                if (tbToken != null) {
                    tbUserInfoVo.setTbTokenName(tbToken.getUserName());
                }
                tbUserInfoVoList.add(tbUserInfoVo);
            }
        }
        //返回到页面分页对象
        Page<TbUserInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tbUserInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 修改会员渠道ID
     *
     * @param tbUserInfoUpdateDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateTbUserInfo(TbUserInfoUpdateDto tbUserInfoUpdateDto) {
        if (tbUserInfoUpdateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }
        TbUserInfo tbUserInfo = tbUserInfoMapper.selectById(tbUserInfoUpdateDto.getId(), tbUserInfoUpdateDto.getMerId());
        tbUserInfo.setSpecialId(tbUserInfoUpdateDto.getSpecialId());
        tbUserInfo.setRelationId(tbUserInfoUpdateDto.getRelationId());
        tbUserInfo.setUpdateTime(DateUtil.getNowTime());
        tbUserInfoMapper.updateById(tbUserInfo);
    }

    /**
     * 删除会员渠道ID
     *
     * @param tbUserInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteTbUserInfo(TbUserInfoIdDto tbUserInfoIdDto) {
        if (tbUserInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }
        tbUserInfoMapper.deleteById(tbUserInfoIdDto.getId(), tbUserInfoIdDto.getMerId());
    }


    /**
     * 修改企业微信用户积分余额
     *
     * @param wxworkUserUpdateBalanceDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateWxworkUserBalance(WxworkUserUpdateBalanceDto wxworkUserUpdateBalanceDto) {

        if (wxworkUserUpdateBalanceDto.getId() == null || wxworkUserUpdateBalanceDto.getBalance() == null || wxworkUserUpdateBalanceDto.getIntegral() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //至少要修改一个
        if (wxworkUserUpdateBalanceDto.getBalance() == null && wxworkUserUpdateBalanceDto.getIntegral() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分和余额至少要修改一项");
        }

        //修改值不能为负数
        if (Tools.getDouble(wxworkUserUpdateBalanceDto.getBalance()).doubleValue() < 0 || Tools.getInteger(wxworkUserUpdateBalanceDto.getIntegral()).intValue() < 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能输入大于0的数");
        }

        if (StringUtils.isNotBlank(wxworkUserUpdateBalanceDto.getRemark())) {
            //判断是否包括表情
            if (EmojiUtil.containsEmoji(wxworkUserUpdateBalanceDto.getRemark())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "原因不能包含表情符号");
            }
        }

        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserUpdateBalanceDto.getId(), wxworkUserUpdateBalanceDto.getMerId());
        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员积分和余额;");
        //AOP切面，封装操作日志内容
        String aspectOperatorLog = "修改余额积分";
        //变更余额
        Double balance = wxworkUserUpdateBalanceDto.getBalance();
        Double changeBalance = 0.0D;
        //表示修改余额
        if (balance != null) {
            //修改类型类型
            Integer balanceType = wxworkUserUpdateBalanceDto.getBalanceType();
            if (balanceType == null) { //修改余额
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入余额修改类型");
            }
            if (!Lists.newArrayList(-1, 0, 1).contains(balanceType)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "余额修改类型值有误");
            }

            //旧余额
            Double oldBalance = Tools.getDouble(wxworkUser.getBalance());
            //新余额
            Double newBalance = 0.00D;
            if (balanceType.intValue() == -1) { //减量
                //减少
                newBalance = Math.sub(oldBalance, balance);
                changeBalance = Math.sub(0, balance);
                aspectOperatorLog = aspectOperatorLog + "；减少余额:" + balance;
            } else if (balanceType.intValue() == 1) { //增量
                //增加
                newBalance = Math.add(oldBalance, balance);
                changeBalance = balance;
                aspectOperatorLog = aspectOperatorLog + "；增加余额:" + balance;
            } else {//修改成指定值
                newBalance = balance;
                changeBalance = Math.sub(newBalance, oldBalance);
                aspectOperatorLog = aspectOperatorLog + "；修改余额:" + balance;
            }
            wxworkUser.setBalance(newBalance);

            content.append("变动余额:" + changeBalance).append(";");
        }


        //表示修改积分
        Integer integral = wxworkUserUpdateBalanceDto.getIntegral();
        //变更积分
        Integer changeIntegral = 0;
        if (integral != null) {
            //修改积分类型
            Integer integralType = wxworkUserUpdateBalanceDto.getIntegralType();
            if (integralType == null) { //修改积分
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入积分修改类型");
            }
            if (!Lists.newArrayList(-1, 0, 1).contains(integralType)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分修改类型值有误");
            }

            //旧积分
            Integer oldIntegral = Tools.getInteger(wxworkUser.getIntegral());
            //新积分
            Integer newIntegral = 0;

            if (integralType.intValue() == -1) { //减量
                //减少
                newIntegral = oldIntegral - integral;
                changeIntegral = 0 - integral;
                aspectOperatorLog = aspectOperatorLog + "；减少积分:" + integral;
            } else if (integralType.intValue() == 1) { //增量
                //增加
                newIntegral = oldIntegral + integral;
                changeIntegral = integral;
                aspectOperatorLog = aspectOperatorLog + "；增加积分:" + integral;
            } else {//修改成指定值
                newIntegral = integral;
                changeIntegral = newIntegral - oldIntegral;
                aspectOperatorLog = aspectOperatorLog + "；修改积分:" + integral;
            }

            wxworkUser.setIntegral(newIntegral);
            content.append("变动积分:" + changeIntegral).append(";");
        }

        Integer nowTime = DateUtil.getNowTime();
        wxworkUser.setUpdateTime(nowTime);
        int j = wxworkUserMapper.updateBalance(wxworkUser);
        if (j != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //增加账号入账明细
        UserAccDetail wxworkUserAccDetail = new UserAccDetail();
        wxworkUserAccDetail.setId(IdWorker.getId());
        wxworkUserAccDetail.setMerId(wxworkUser.getMerId());
        wxworkUserAccDetail.setUserId(wxworkUser.getId());
        wxworkUserAccDetail.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
        wxworkUserAccDetail.setDeviceType(wxworkUser.getDeviceType());
        wxworkUserAccDetail.setChangeInte(wxworkUserUpdateBalanceDto.getIntegral());
        wxworkUserAccDetail.setChangeBal(wxworkUserUpdateBalanceDto.getBalance());
        wxworkUserAccDetail.setNewBal(wxworkUser.getBalance());
        wxworkUserAccDetail.setNewInte(wxworkUser.getIntegral());
        wxworkUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
        wxworkUserAccDetail.setRemark(wxworkUserUpdateBalanceDto.getRemark());
        wxworkUserAccDetail.setCreateTime(nowTime);
        wxworkUserAccDetail.setUpdateTime(nowTime);
        int insert = userAccDetailMapper.insert(wxworkUserAccDetail);
        if (insert != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
        }

        //AOP切面，封装操作日志内容
        wxworkUserUpdateBalanceDto.setAspectOperatorLog(aspectOperatorLog);

        //发送异常报警通知-修改会员敏感信息
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(wxworkUserUpdateBalanceDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员敏感信息
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, wxworkUserUpdateBalanceDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        if (loginVo == null) {
            loginVo = new LoginVo();
        }
        ext.put("childuser", loginVo.getLoginName());
        ext.put("content", content.toString());
        ext.put("nick", wxworkUser.getNickName());
        ext.put("wxid", wxworkUser.getBizUserId());
        ext.put("userid", wxworkUser.getId());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

    }

    /**
     * 修改企业微信用户定向比例
     *
     * @param wxworkUserUpdatePriRewardRulesDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateWxworkUserPriRewardRules(WxworkUserUpdatePriRewardRulesDto wxworkUserUpdatePriRewardRulesDto) {
        if (wxworkUserUpdatePriRewardRulesDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserUpdatePriRewardRulesDto.getId(), wxworkUserUpdatePriRewardRulesDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取设置定向规则JSON对象
        Map<String, PriRewardRulesDto> priRewardRules = JSONObject.parseObject(wxworkUser.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>() {
        });
        if (priRewardRules == null) {
            priRewardRules = new HashMap<>();
        }

        //获取该运营商开启的产品模块
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(wxworkUserUpdatePriRewardRulesDto.getMerId(), MerConfigKeyEnum.PRODUCT_SWITCH.getValue());
        if (merBaseConfig != null) {
            //获取该运营商开启的产品模块
            List<String> productKeyList = JSONObject.parseArray(merBaseConfig.getVal(), String.class);
            if (productKeyList != null && productKeyList.size() > 0) {
                //是否包含淘宝
                if (productKeyList.contains(ProductKeyEnum.TB.getValue())) {
                    PriRewardRulesDto tbRule = wxworkUserUpdatePriRewardRulesDto.getTbRule();
//                    if(tbRule != null){
//                        Long priRuleId = tbRule.getPriRuleId();
//                        if(priRuleId == null){
//                            tbRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("tbRule", tbRule);
                }

                //是否包含京东
                if (productKeyList.contains(ProductKeyEnum.JD.getValue())) {
                    PriRewardRulesDto jdRule = wxworkUserUpdatePriRewardRulesDto.getJdRule();
//                    if(jdRule != null){
//                        Long priRuleId = jdRule.getPriRuleId();
//                        if(priRuleId == null){
//                            jdRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("jdRule", jdRule);
                }

                //是否包含拼多多
                if (productKeyList.contains(ProductKeyEnum.PDD.getValue())) {
                    PriRewardRulesDto pddRule = wxworkUserUpdatePriRewardRulesDto.getPddRule();
//                    if(pddRule != null){
//                        Long priRuleId = pddRule.getPriRuleId();
//                        if(priRuleId == null){
//                            pddRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("pddRule", pddRule);
                }

                //是否包含唯品会
                if (productKeyList.contains(ProductKeyEnum.VPH.getValue())) {
                    PriRewardRulesDto vphRule = wxworkUserUpdatePriRewardRulesDto.getVphRule();
//                    if(vphRule != null){
//                        Long priRuleId = vphRule.getPriRuleId();
//                        if(priRuleId == null){
//                            vphRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("vphRule", vphRule);
                }

                //是否包含本地生活
                if (productKeyList.contains(ProductKeyEnum.LOCAL_LIVE.getValue())) {
                    PriRewardRulesDto localLiveRule = wxworkUserUpdatePriRewardRulesDto.getLocalLiveRule();
//                    if(localLiveRule != null){
//                        Long priRuleId = localLiveRule.getPriRuleId();
//                        if(priRuleId == null){
//                            localLiveRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("localLiveRule", localLiveRule);
                }

                //是否包含抖音
                if (productKeyList.contains(ProductKeyEnum.DY.getValue())) {
                    PriRewardRulesDto dyRule = wxworkUserUpdatePriRewardRulesDto.getDyRule();
//                    if(dyRule != null){
//                        Long priRuleId = dyRule.getPriRuleId();
//                        if(priRuleId == null){
//                            dyRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("dyRule", dyRule);
                }

                //是否包含抖音
                if (productKeyList.contains(ProductKeyEnum.KS.getValue())) {
                    PriRewardRulesDto ksRule = wxworkUserUpdatePriRewardRulesDto.getKsRule();
//                    if(dyRule != null){
//                        Long priRuleId = dyRule.getPriRuleId();
//                        if(priRuleId == null){
//                            dyRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("ksRule", ksRule);
                }
            }
        }

        wxworkUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRules)));
        wxworkUser.setUpdateTime(DateUtil.getNowTime());

        wxworkUserMapper.updateByIdSelective(wxworkUser);


        //修改ES
        try {
            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_WORK_WECHAT.getKey() + "_" + wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
            //查询会员基本信息
            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId()), uzai_user_ext_info_id, null);
            if (dataMp_ext != null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("priRewardRules", Tools.getStr(wxworkUser.getPriRewardRules()));  //修改定向比例
                jsonObject.put("updateTime", DateUtil.getNowTime());

                elasticsearchUtil.updateDataById(jsonObject, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        } catch (Exception e) {
            logger.error("删除ES会员扩展信息出现异常:{}" + e.getMessage());
        }

    }

    /**
     * 修改微信用户会员标签
     *
     * @param userUpdateMarketingTagDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateSysTags(UserUpdateMarketingTagDto userUpdateMarketingTagDto) {
        if (userUpdateMarketingTagDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
        }

        WxworkUser wxworkUser = wxworkUserMapper.selectById(userUpdateMarketingTagDto.getId(), userUpdateMarketingTagDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        wxworkUser.setSysTags(Tools.getStrEmpty(JSONObject.toJSONString(userUpdateMarketingTagDto.getSysTagList())));

        wxworkUserMapper.updateSysTags(wxworkUser);

    }

    /**
     * 加入黑名单
     *
     * @param wxworkUserAddBlackDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void addBlackUser(WxworkUserAddBlackDto wxworkUserAddBlackDto) {
        if (wxworkUserAddBlackDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserAddBlackDto.getId(), wxworkUserAddBlackDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员不存在");
        }

        Integer now = DateUtil.getNowTime();

        //查询是否已经在黑名单当中
        //id为merId_wxid
        String id = wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
        Map<String, Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
        WechatBlacklistPrv wechatBlacklistPrv = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
        if (wechatBlacklistPrv != null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在黑名单中");
        }
        //添加到全网黑名单
        if (wxworkUserAddBlackDto.getAllBackFlag() != null && wxworkUserAddBlackDto.getAllBackFlag().intValue() == 1) {
            Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxworkUser.getBizUserId(), null);
            WechatBlacklistPub wechatBlacklistPub = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
            if (wechatBlacklistPub != null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在共享黑名单里");
            }
        }

        if (wechatBlacklistPrv == null) {
            wechatBlacklistPrv = new WechatBlacklistPrv();
            wechatBlacklistPrv.setId(id);
            wechatBlacklistPrv.setMerId(wxworkUser.getMerId());
            wechatBlacklistPrv.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
            wechatBlacklistPrv.setDeviceType(wxworkUser.getDeviceType());
            wechatBlacklistPrv.setWxid(wxworkUser.getBizUserId());
            wechatBlacklistPrv.setNickName(wxworkUser.getNickName());
            wechatBlacklistPrv.setHeadImg(wxworkUser.getHeadImg());
            wechatBlacklistPrv.setType(wxworkUserAddBlackDto.getUserBlackType());
            wechatBlacklistPrv.setCreateTime(now);
            wechatBlacklistPrv.setRemark(wxworkUserAddBlackDto.getRemark());
            wechatBlacklistPrv.setUpdateTime(now);
            elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);

            //添加到全网黑名单
            if (wxworkUserAddBlackDto.getAllBackFlag() != null && wxworkUserAddBlackDto.getAllBackFlag().intValue() == 1) {
                Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxworkUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if (wechatBlacklistPub == null) {
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(wxworkUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(now);
                    wechatBlacklistPub.setUpdateTime(now);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxworkUser.getBizUserId());
                }
            }
        }

        //修改会员备注、通讯录备注、发送修改微信终端修改配置指令
        if (Tools.getInteger(wxworkUserAddBlackDto.getUpdateRemarkFlag()).intValue() == 1 && StringUtils.isNotBlank(wxworkUserAddBlackDto.getRemark())) {
            wxworkUser.setRemark(wxworkUserAddBlackDto.getRemark());
            userOperatorService.updateRemarkByUserAndContacts(wxworkUser);
        }

        try {
            //延迟0.5秒
            Thread.sleep(500);
        } catch (Exception e) {

        }
    }

    /**
     * 修改企业微信用户详情信息
     *
     * @param wxworkUserInfoUpdateDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateWxworkUserInfo(WxworkUserInfoUpdateDto wxworkUserInfoUpdateDto) {

        if (wxworkUserInfoUpdateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserInfoUpdateDto.getId(), wxworkUserInfoUpdateDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取运营商ID
        Long merId = wxworkUser.getMerId();
        //用户Id
        Long id = wxworkUser.getId();

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员信息;");

        //微信昵称
        if (!Tools.getStr(wxworkUserInfoUpdateDto.getNickName()).equals(Tools.getStr(wxworkUser.getNickName()))) {
            wxworkUser.setNickName(Tools.getStr(wxworkUserInfoUpdateDto.getNickName()));
        }

        //会员类型
        if (wxworkUserInfoUpdateDto.getUserType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不能为空");
        }
        UserType userType = userTypeMapper.selectById(wxworkUserInfoUpdateDto.getUserType(), wxworkUser.getMerId());
        if (userType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不存在或已删除");
        }

        //会员类型
        if (Tools.getLong(wxworkUserInfoUpdateDto.getUserType()).longValue() != Tools.getLong(wxworkUser.getUserType()).longValue()) {
            wxworkUser.setUserType(wxworkUserInfoUpdateDto.getUserType());
            content.append("新会员类型:" + userType.getName()).append(";");
        }

        //支付宝姓名
        //是否修改了支付宝信息标志
        Boolean updateAlipayInfoFlag = false;
        if (!Tools.getStr(wxworkUserInfoUpdateDto.getAlipayName()).equals(Tools.getStr(wxworkUser.getAlipayName()))) {
            wxworkUser.setAlipayName(wxworkUserInfoUpdateDto.getAlipayName());
            updateAlipayInfoFlag = true;
        }

        //支付宝账号
        if (!Tools.getStr(wxworkUserInfoUpdateDto.getAlipayAccount()).equals(Tools.getStr(wxworkUser.getAlipayAccount()))) {
            wxworkUser.setAlipayAccount(wxworkUserInfoUpdateDto.getAlipayAccount());
            updateAlipayInfoFlag = true;
        }

        //淘宝订单尾号
//        if(Tools.getInteger(wxworkUserInfoUpdateDto.getTbLastOrderNo()).intValue() != Tools.getInteger(wxworkUser.getTbLastOrderNo()).intValue()){
//            wxworkUser.setTbLastOrderNo(Tools.getInteger(wxworkUserInfoUpdateDto.getTbLastOrderNo()));
//        }

        //最后下单时间
        if (Tools.getInteger(wxworkUserInfoUpdateDto.getLastOrderTime()).intValue() != Tools.getInteger(wxworkUser.getLastOrderTime()).intValue()) {
            wxworkUser.setLastOrderTime(Tools.getInteger(wxworkUserInfoUpdateDto.getLastOrderTime()));
        }

        //机器人ID
        if (Tools.getLong(wxworkUserInfoUpdateDto.getDeviceUniqueId()).longValue() != Tools.getLong(wxworkUser.getDeviceUniqueId()).longValue()) {

            //需要验证新机器人和旧机器人是否在同一个会员类型组
            DeviceWxworkInfo deviceWxworkInfo_new = deviceWxworkInfoMapper.selectById(wxworkUserInfoUpdateDto.getDeviceUniqueId(), wxworkUserInfoUpdateDto.getMerId());
            if (deviceWxworkInfo_new == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人不存在");
            }

            ConfigPlan configPlan = configPlanMapper.selectById(deviceWxworkInfo_new.getConfigId(), deviceWxworkInfo_new.getMerId());
            if (configPlan == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人的配置方案不存在");
            }

            if (Tools.getLong(configPlan.getUserTypeGroupId()).longValue() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人的配置方案还未配置会员类型组");
            }

            //验证会员所在会员类型组是否跟新选组机器人所在配置方案里配置的会员类型组是否一样，如果不一样，则不能修改
            if (Tools.getLong(userType.getGroupId()).longValue() != Tools.getLong(configPlan.getUserTypeGroupId()).longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新选择的机器人配置的会员类型组与会员的类型组不一样，不能修改");
            }

            wxworkUser.setDeviceUniqueId(wxworkUserInfoUpdateDto.getDeviceUniqueId());
            content.append("新机器人唯一id:" + Tools.getLong(wxworkUserInfoUpdateDto.getDeviceUniqueId())).append(";");
        }

        //标签
        List<String> addTagsList = wxworkUserInfoUpdateDto.getTagsArr();
        String tagsStr = Tools.getStrEmpty(JSONObject.toJSONString(addTagsList));
        if (!tagsStr.equals(Tools.getStrEmpty(wxworkUser.getTags()))) {
            wxworkUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(addTagsList)));
        }

        //会员标签
        List<SysTagVo> sysTagsList = wxworkUserInfoUpdateDto.getSysTagsList();
        String sysTagsStr = Tools.getStrEmpty(JSONObject.toJSONString(sysTagsList));
        if (!sysTagsStr.equals(Tools.getStrEmpty(wxworkUser.getSysTags()))) {
            wxworkUser.setSysTags(sysTagsStr);
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        if (!Tools.getStr(wxworkUserInfoUpdateDto.getRemark()).equals(Tools.getStr(wxworkUser.getRemark()))) { //修改了备注
            //备注
            wxworkUser.setRemark(wxworkUserInfoUpdateDto.getRemark());
            setRemarkFlag = true;
        }

        //身份
        if (wxworkUserInfoUpdateDto.getIdentity() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "身份不能为空");
        }

        if (userType.getIdentity().intValue() != wxworkUserInfoUpdateDto.getIdentity().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的会员类型与会员身份不一样");
        }

        //是否修改身份证标志
        boolean flag_identity = false;
        //旧身份
        int identityOld = wxworkUser.getIdentity().intValue();
        //新身份
        int identityNew = wxworkUserInfoUpdateDto.getIdentity().intValue();

        //旧上级买家
        long parentIdOld = Tools.getLong(wxworkUser.getParentId()).longValue();

        //旧代理
        long agentIdOld = Tools.getLong(wxworkUser.getAgentId()).longValue();

        //旧合伙人
        long partnerIdOld = Tools.getLong(wxworkUser.getPartnerId()).longValue();

        //旧身份自己买家树
        String parentInfoOld_wo = Tools.getStr(wxworkUser.getParentInfo());

        //旧身份的所有下级的上级买家树
        String parentInfoOld_son = null;
        if (parentIdOld != 0) {
            parentInfoOld_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", parentInfoOld_wo);
        } else {
            parentInfoOld_son = String.valueOf(wxworkUser.getId());
        }

        //旧身份自己的代理树
        String agentInfoOld_wo = Tools.getStr(wxworkUser.getAgentInfo());

        //旧身份的下级的代理树
        String agentInfoOld_son = null;
        if (agentIdOld != 0) {
            agentInfoOld_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", agentInfoOld_wo);
        } else {
            agentInfoOld_son = String.valueOf(wxworkUser.getId());
        }

        //如果新身份是合伙人:合伙人、代理、上级买家全部清空
        if (identityNew == IdentityEnum.PARTNER.getId()) {
            wxworkUserInfoUpdateDto.setPartnerId(0L); //修改合伙人
            wxworkUserInfoUpdateDto.setAgentId(0L); //修改代理
            wxworkUserInfoUpdateDto.setParentId(0L); //修改上级买家
        } else if (identityNew == IdentityEnum.AGENT.getId()) { //如果新身份是代理:上级买家清空
            wxworkUserInfoUpdateDto.setParentId(0L);
        }

        //判断是否修改了身份
        if (identityNew != identityOld) { //修改身份
            flag_identity = true;       //修改身份标志为true
            wxworkUser.setIdentity(identityNew); //修改身份属性值
            content.append("新身份:" + IdentityEnum.getById(identityNew).getDesc()).append(";");
        }

        //新上级买家
        long parentIdNew = Tools.getLong(wxworkUserInfoUpdateDto.getParentId()).longValue();

        //新代理
        long agentIdNew = Tools.getLong(wxworkUserInfoUpdateDto.getAgentId()).longValue();

        //新合伙人
        long partnerIdNew = Tools.getLong(wxworkUserInfoUpdateDto.getPartnerId()).longValue();

        //验证合伙人ID是否为合伙人
        boolean flag_partner = false;
        if (partnerIdNew != partnerIdOld) { //修改了合伙人

            //标志合伙人已经修改
            flag_partner = true;

            wxworkUser.setPartnerId(partnerIdNew); //修改自己的合伙人信息

            //选择了合伙人，验证对方身份
            if (partnerIdNew != 0) {
                WxworkUser wxworkUserPartner_new = wxworkUserMapper.selectById(partnerIdNew, wxworkUserInfoUpdateDto.getMerId());
                //判断存不存在
                if (wxworkUserPartner_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if (wxworkUserPartner_new.getIdentity() == null || wxworkUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if (wxworkUserPartner_new.getId().longValue() == wxworkUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
                content.append("新合伙人:" + partnerIdNew).append(";");
            } else {
                content.append("清空合伙人").append(";");
            }
        }

        //验证上级会员ID是否为买家
        boolean flag_parent = false;
        String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
        String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的
        if (parentIdNew != parentIdOld) {//修改了上级买家
            //标志上级买家已经修改
            flag_parent = true;
            //修改上级买家ID
            wxworkUser.setParentId(parentIdNew);

            //验收上级买家
            if (parentIdNew != 0) { //选择了上级买家
                WxworkUser wxworkUserParent_new = wxworkUserMapper.selectById(parentIdNew, wxworkUserInfoUpdateDto.getMerId());
                //判断存不存在
                if (wxworkUserParent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }
                //判断身份
                if (wxworkUserParent_new.getIdentity() == null || wxworkUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if (wxworkUserParent_new.getId().longValue() == wxworkUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(wxworkUserParent_new.getParentInfo());
                if (parentInfo.contains(String.valueOf(wxworkUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }
                //判断新上级买家是否有上级买家，
                if (Tools.getLong(wxworkUserParent_new.getParentId()).longValue() != 0) {//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(wxworkUserParent_new.getId()), "_", wxworkUserParent_new.getParentInfo());
                    wxworkUser.setParentInfo(parentInfoNew_wo);
                } else {
                    parentInfoNew_wo = String.valueOf(wxworkUserParent_new.getId());
                    wxworkUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", parentInfoNew_wo);

                content.append("新上级:" + parentIdNew).append(";");

            } else { //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                wxworkUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(wxworkUser.getId());

                content.append("清空上级").append(";");
            }
        }

        //验证代理身份是否为代理人
        boolean flag_agent = false;
        String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
        String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的
        if (agentIdNew != agentIdOld) { //表示修改了上级代理
            //标志上级代理已经修改
            flag_agent = true;
            //修改代理属性
            wxworkUser.setAgentId(agentIdNew);

            if (agentIdNew != 0) { //选择了上级代理，需要验证身份
                WxworkUser wxworkUserAgent_new = wxworkUserMapper.selectById(agentIdNew, wxworkUserInfoUpdateDto.getMerId());
                //判断存不存在
                if (wxworkUserAgent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if (wxworkUserAgent_new.getIdentity() == null || wxworkUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if (wxworkUserAgent_new.getId().longValue() == wxworkUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(wxworkUserAgent_new.getAgentInfo());
                if (agentInfo.contains(String.valueOf(wxworkUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if (Tools.getLong(wxworkUserAgent_new.getAgentId()) != 0) { //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(wxworkUserAgent_new.getId()), "_", wxworkUserAgent_new.getAgentInfo());
                    wxworkUser.setAgentInfo(agentInfoNew_wo);
                } else {
                    agentInfoNew_wo = String.valueOf(wxworkUserAgent_new.getId());
                    wxworkUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", agentInfoNew_wo);

                content.append("新代理:" + agentIdNew).append(";");

            } else { //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                wxworkUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(wxworkUser.getId());
                content.append("清空代理").append(";");
            }
        }

        //修改企业微信用户详情信息
        wxworkUserMapper.updateById(wxworkUser);

        //修改身份，改变了其他用户的树
        if (flag_identity) {
            //判断旧身份类型
            if (identityOld == IdentityEnum.BUYER.getId()) { // 旧身份是买家
                //判断新身份
                if (identityNew == IdentityEnum.AGENT.getId()) { //新身份是代理

                    /**买家转代理-身份往上升
                     * 1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                     * 2:修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                    wxworkUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfoNew_son, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    wxworkUserMapper.batchUpdateParentInfo("%_" + parentInfoOld_son, "", merId, true);
                    wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    wxworkUserQuery.setMerId(merId);
                    wxworkUserQuery.setParentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                    //查询总数
                    Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                    //有总数，且最小创建时间有
                    if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                                    for (WxworkUser wxworkUser_son : wxworkUserList) {
                                        wxworkUser_son.setParentId(0L);   //清空上级
                                        wxworkUser_son.setParentInfo(""); //清空上级树
                                        wxworkUser_son.setAgentId(id);    //修改代理
                                        wxworkUser_son.setAgentInfo(agentInfoNew_son); //修改代理树
                                        wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                        wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                        //4:将下N级代理和下N级代理的树更新
                                        String agentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                        String agentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getAgentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.PARTNER.getId()) { //新身份是合伙人

                    /**买家转合伙人-身份往上升
                     * 1: 批量将下N级无合伙人的用户合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                     * 2:修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无合伙人的合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                    wxworkUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    wxworkUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    wxworkUserQuery.setMerId(merId);
                    wxworkUserQuery.setParentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                    //查询总数
                    Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                    //有总数，且最小创建时间有
                    if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                                    for (WxworkUser wxworkUser_son : wxworkUserList) {
                                        wxworkUser_son.setParentId(0L);   //清空上级
                                        wxworkUser_son.setParentInfo(""); //清空上级树
                                        wxworkUser_son.setPartnerId(id);    //修改合伙人
                                        wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                        wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (identityOld == IdentityEnum.AGENT.getId()) { //旧身份是代理
                //判断新身份
                if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                    /**代理转买家-身份往下降
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                     *  2:修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                    //wxworkUserMapper.batchUpdateParentInfoFromAgentInfoAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);

                    //2:修改下N级代理树
                    //分俩次替换（避免替换留下"_"符合）
                    wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_wo, merId, true);
                    wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_wo, merId, false);

                    //3: 修改下级的代理和代理树
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    wxworkUserQuery.setMerId(merId);
                    wxworkUserQuery.setAgentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                    //查询总数
                    Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                    //有总数，且最小创建时间有
                    if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                                    for (WxworkUser wxworkUser_son : wxworkUserList) {
                                        wxworkUser_son.setAgentId(agentIdNew);           // 修改新的上级代理
                                        wxworkUser_son.setAgentInfo(agentInfoNew_wo);    //修改新的代理树

                                        //买家为空，且身份是买家
                                        if (wxworkUser_son.getParentId().longValue() == 0L && wxworkUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                            wxworkUser_son.setParentId(id);                  //修改上级
                                            wxworkUser_son.setParentInfo(parentInfoNew_son); //修改上级树
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                            String parentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            wxworkUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }
                                        wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                        wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.PARTNER.getId()) { //新身份是合伙人

                    /**代理转合伙人-身份往上升
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                     *  2:修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无合伙人的会员，将合伙人设置为此Id，满足条件:A:代理树包含此ID，B:合伙人为空；
                    wxworkUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);
                    //2:修改下N级代理树(清空截断）
                    //分俩次替换（避免替换留下"_"符合）
                    wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "", merId, true);
                    wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_son, "", merId, false);
                    //3: 修改下级的代理和代理树
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    wxworkUserQuery.setMerId(merId);
                    wxworkUserQuery.setAgentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                    //查询总数
                    Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                    //有总数，且最小创建时间有
                    if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                                    for (WxworkUser wxworkUser_son : wxworkUserList) {
                                        wxworkUser_son.setAgentId(0L);                    // 清空代理人
                                        wxworkUser_son.setAgentInfo("");                  //清空代理人信息
                                        wxworkUser_son.setPartnerId(id);                  //修改合伙人
                                        wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                        wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                    }
                                }
                            }
                        }
                    }
                }
            } else { //旧身份是合伙人
                //判断新身份
                if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                    /**合伙人转买家-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                     *  2:清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                    //wxworkUserMapper.batchUpdateParentInfoFromPartnerIdAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);
                    //2:清空下N合伙人信息,更新买家信息
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    wxworkUserQuery.setMerId(merId);
                    wxworkUserQuery.setPartnerId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                    //查询总数
                    Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                    //有总数，且最小创建时间有
                    if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                                    for (WxworkUser wxworkUser_son : wxworkUserList) {
                                        wxworkUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是买家
                                        if (wxworkUser_son.getParentId().longValue() == 0L && wxworkUser_son.getAgentId().longValue() == 0L && wxworkUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                            wxworkUser_son.setParentId(id);                   //修改上级
                                            wxworkUser_son.setParentInfo(parentInfoNew_son);  //修改上级树
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                            String parentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            wxworkUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }
                                        wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                        wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.AGENT.getId()) { //新身份是代理

                    /**合伙人转代理-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                     *  2:清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                    //wxworkUserMapper.batchUpdateAgentInfoFromPartnerIdAndAgentIdNull(id, parentInfoNew_son, merId, 0);
                    //2:清空下N合伙人信息,更新买家信息
                    WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                    wxworkUserQuery.setMerId(merId);
                    wxworkUserQuery.setPartnerId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                    //查询总数
                    Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                    //有总数，且最小创建时间有
                    if (wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                                    for (WxworkUser wxworkUser_son : wxworkUserList) {

                                        wxworkUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是代理
                                        if (wxworkUser_son.getParentId().longValue() == 0L && wxworkUser_son.getAgentId().longValue() == 0L && wxworkUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()) {
                                            wxworkUser_son.setAgentId(id);                   //修改代理
                                            wxworkUser_son.setAgentInfo(agentInfoNew_son);  //修改代理树

                                            //将下N级代理和下N级的代理树更新
                                            String agentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                            String agentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getAgentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                            wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                        }

                                        wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                        wxworkUserMapper.updateIdentityInfo(wxworkUser_son);

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //如果修改了上级买家,批量修改下N级买家树
        if (flag_parent) {
            //分俩次替换（避免替换留下"_"符合）
            wxworkUserMapper.batchUpdateParentInfo("%_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);
        }

        //如果修改了代理,批量修改下N级代理树
        if (flag_agent) {
            //分俩次替换（避免替换留下"_"符合）
            wxworkUserMapper.batchUpdateAgentInfo("%_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);
        }

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if (setRemarkFlag) {
            //查询机器人
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUser.getDeviceUniqueId(), merId);
            if (deviceWxworkInfo != null) {
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
                msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                msgDto.setMerId(wxworkUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(wxworkUser.getBizUserId());
                setUserRemarkDto.setRemark(Tools.getStr(wxworkUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }

        //是否修改了支付宝账号和姓名
        if (updateAlipayInfoFlag) {
            AlipayUserAuthDto alipayUserAuthDto = new AlipayUserAuthDto();
            alipayUserAuthDto.setAlipayUserId(wxworkUser.getAlipayAccount());
            alipayUserAuthDto.setAlipayUserName(wxworkUser.getAlipayName());
            alipayUserAuthDto.setUserId(String.valueOf(wxworkUser.getId()));
            //获取该会员的appid配置1-获取默认机器人;2-获取机器人的配置方案；3-从配置方案的提现配置里获取appid
            if (wxworkUser.getDeviceUniqueId() != null) {
                DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUser.getDeviceUniqueId(), wxworkUser.getMerId());
                if (deviceWxworkInfo != null && deviceWxworkInfo.getConfigId() != null) {
                    ConfigPlan configPlan = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
                    if (configPlan != null && configPlan.getUserTakeBalId() != null) {
                        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlan.getMerId());
                        if (sysPlugin != null && StringUtils.isNotBlank(sysPlugin.getData())) {
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                                String zf_app_id = jsonObject.getString("zf_app_id");//账房appId
                                if (StringUtils.isNotBlank(zf_app_id)) {
                                    alipayUserAuthDto.setAppId(zf_app_id);
                                    UzaiRespVo<Object> objectUzaiRespVo = uzaiCashierServerFeignService.alipayUserAuth(alipayUserAuthDto);
                                    logger.info("--调用账房授权支付宝账号信息微服务接口--para={},result={}", JSONObject.toJSONString(alipayUserAuthDto), JSONObject.toJSONString(objectUzaiRespVo));
                                }
                            } catch (Exception e) {
                                logger.error("---配置方案的提现设置插件格式有问题---sysPluginId={}, configId={}, merId={}", sysPlugin.getId(), configPlan.getId(), configPlan.getMerId());
                            }
                        }
                    }
                }
            }
        }

        //发送异常报警通知-修改会员敏感信息
        if (StringUtils.isNotBlank(content)) {
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(wxworkUserInfoUpdateDto.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, wxworkUserInfoUpdateDto.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", wxworkUser.getNickName());
            ext.put("wxid", wxworkUser.getBizUserId());
            ext.put("userid", wxworkUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员敏感信息报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);


        }

        //修改ES缓存
        //修改ES
        try {
            //修改营销策略数据
            if (flag_parent || flag_agent || flag_partner) {
                marketingRewardsService.updateMarketingRewards(wxworkUser);
            }

            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_WORK_WECHAT.getKey() + "_" + wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
            //查询会员基本信息
            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId()), uzai_user_ext_info_id, null);
            if (dataMp_ext != null) {
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(wxworkUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        } catch (Exception e) {
            logger.error("修改会员营销策略信息出现异常:{}" + e.getMessage());
        }

        //订阅信息。调用服务修改
    }

    /**
     * 用户发送消息
     *
     * @param wxworkUserSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void sendMessageToOneUser(WxworkUserSendMsgDto wxworkUserSendMsgDto) {

        if (wxworkUserSendMsgDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID参数不能为空");
        }

        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserSendMsgDto.getId(), wxworkUserSendMsgDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        if (StringUtils.isBlank(wxworkUserSendMsgDto.getMessage())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息为空 ");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxworkUser.getDeviceUniqueId(), wxworkUser.getDeviceType(), wxworkUserSendMsgDto.getMerId());
        if (device == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
        }

        //调用API服务发送消息
        // TODO: 2021/9/4  发送消息
        //发送MQ消息
        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
        NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
        msgDto.setContent(noticeMsgDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(device.getRecvmsgType());
        msgDto.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
        msgDto.setMerId(wxworkUser.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
        noticeMsgDto.setContent(wxworkUserSendMsgDto.getMessage());
        noticeMsgDto.setBizUserId(wxworkUser.getBizUserId());
        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
        noticeMsgDto.setGroupId(null);
        noticeMsgDto.setNickName(wxworkUser.getNickName());
        noticeMsgDto.setMsgSource(1);
        noticeMsgDto.setDelay(0);
        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
        noticeMsgPushProducerService.sendMessage(msgDto);

    }

    /**
     * 单个用户修改信息
     *
     * @param wxworkUserUpdateDt
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateToOneUser(WxworkUserUpdateDto wxworkUserUpdateDt) {

        //修改时间
        Integer nowTime = DateUtil.getNowTime();

        if (wxworkUserUpdateDt.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID不存在");
        }

        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserUpdateDt.getId(), wxworkUserUpdateDt.getMerId());
        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        //修改用户类型
        //查询新的用户类型
        if (wxworkUserUpdateDt.getUserType() != null) {
            UserType userType_new = userTypeMapper.selectById(wxworkUserUpdateDt.getUserType(), wxworkUserUpdateDt.getMerId());
            //新会员类型不为空
            if (userType_new != null) {
                if (userType_new.getId().longValue() != wxworkUser.getUserType().longValue()) {//修改了会员类型（修改了身份）
                    //需判断新会员类型是否跟旧会员类型在同一个组内，不同组内不能修改。否则会造成用户的会员类型组和绑定机器人配置方案里的会员类型组不一样
                    UserType userType_old = userTypeMapper.selectById(wxworkUser.getUserType(), wxworkUser.getMerId());
                    if (userType_old != null) {
                        if (userType_old.getGroupId().longValue() == userType_new.getGroupId().longValue()) { //如果不相等，表示不在同一个组内，则不让修改会员类型
                            WxworkUpdateIdentityDto wxworkUpdateIdentityDto = new WxworkUpdateIdentityDto();
                            wxworkUpdateIdentityDto.setMerId(wxworkUserUpdateDt.getMerId());
                            wxworkUpdateIdentityDto.setId(wxworkUser.getId());
                            wxworkUpdateIdentityDto.setUserTypeNew(wxworkUserUpdateDt.getUserType());
                            wxworkUpdateIdentityDto.setIdentityNew(userType_new.getIdentity());
                            wxworkUserTreeInfoService.updateIdentity(wxworkUpdateIdentityDto);
                        }
                    }
                }
            }
        }

        //修改定向规则
        //获取用户本身旧的定向规则JSON对象
        Map<String, PriRewardRulesDto> priRewardRulesMap_old = JSONObject.parseObject(wxworkUser.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>() {
        });
        if (priRewardRulesMap_old == null) {
            priRewardRulesMap_old = new HashMap<>();
        }

        //获取页面设置的新的定向规则JSON对象
        Map<String, PriRewardRulesDto> priRewardRulesMap_new = JSONObject.parseObject(wxworkUserUpdateDt.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>() {
        });
        if (priRewardRulesMap_new != null && priRewardRulesMap_new.size() > 0) {
            for (String key : priRewardRulesMap_new.keySet()) {
                //新定向规则
                PriRewardRulesDto priRewardRulesDto_new = priRewardRulesMap_new.get(key);
                //旧定向规则
                PriRewardRulesDto priRewardRulesDto_old = priRewardRulesMap_old.get(key);
                if (priRewardRulesDto_old == null) {
                    priRewardRulesDto_old = new PriRewardRulesDto();
                }
                //判断新的定向规则值
                if (priRewardRulesDto_new != null) {
                    //判断定向规则
                    if (priRewardRulesDto_new.getPriRuleId() != null) { //表示修改
                        if (priRewardRulesDto_new.getPriRuleId().longValue() < 0) { //表示清空
                            priRewardRulesDto_old.setPriRuleId(null);
                        } else {//表示修改
                            priRewardRulesDto_old.setPriRuleId(priRewardRulesDto_new.getPriRuleId());
                        }
                    }
                    //判断阶梯规则
                    if (priRewardRulesDto_new.getLadderId() != null) { //表示修改
                        if (priRewardRulesDto_new.getLadderId().longValue() < 0) { //表示清空
                            priRewardRulesDto_old.setLadderId(null);
                        } else {//表示修改
                            priRewardRulesDto_old.setLadderId(priRewardRulesDto_new.getLadderId());
                        }
                    }
                }
                //更新旧的定向规则
                priRewardRulesMap_old.put(key, priRewardRulesDto_old);
            }
        }
        //修改定向规则
        wxworkUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRulesMap_old)));
        wxworkUserMapper.updatePriRewardRules(wxworkUser);

        //是否增加标签
        List<String> userLabList = wxworkUserUpdateDt.getUserLabList();
        //是否清空标签
        Integer cleanLab = wxworkUserUpdateDt.getCleanLab();
        //清空指定标签列表
        List<String> cleanUserLabList = wxworkUserUpdateDt.getCleanUserLabList();

        //开启清空所有标签
        if (cleanLab != null && cleanLab.intValue() == 1) {
            //添加新标签
            if (userLabList != null && userLabList.size() > 0) {
                wxworkUser.setTags(JSONObject.toJSONString(userLabList));
            } else {
                wxworkUser.setTags("");
            }
        } else { //未开启清空所有标签

            //旧标签
            String tags_old = wxworkUser.getTags();
            List<String> tagsOldList = JSONObject.parseArray(tags_old, String.class);
            if (tagsOldList == null) {
                tagsOldList = new ArrayList<>();
            }

            //清空指定标签列表
            if (cleanUserLabList != null && cleanUserLabList.size() > 0) {
                tagsOldList.removeAll(cleanUserLabList);
            }

            //添加新标签
            if (userLabList != null && userLabList.size() > 0) {
                tagsOldList.addAll(userLabList);
            }

            //去重复
            tagsOldList = tagsOldList.stream().distinct().collect(Collectors.toList());
            wxworkUser.setTags(JSONObject.toJSONString(tagsOldList));
        }

        //是否增加新会员标签列表
        List<SysTagVo> sysTagsList = wxworkUserUpdateDt.getSysTagsList();
        //是否清空所有会员标签
        Integer cleanSysTags = wxworkUserUpdateDt.getCleanSysTags();
        //清空指定会员标签列表
        List<SysTagVo> cleanSysTagsList = wxworkUserUpdateDt.getCleanSysTagsList();

        //开启清空所有会员标签
        if (cleanSysTags != null && cleanSysTags.intValue() == 1) {
            //添加新会员标签
            if (sysTagsList != null && sysTagsList.size() > 0) {
                wxworkUser.setSysTags(JSONObject.toJSONString(sysTagsList));
            } else {
                wxworkUser.setSysTags("");
            }
        } else {//未开启清空会员标签
            //旧会员标签
            String sysTags_old = wxworkUser.getSysTags();
            List<SysTagVo> sysTagsOldList = JSONObject.parseArray(sysTags_old, SysTagVo.class);
            if (sysTagsOldList == null) {
                sysTagsOldList = new ArrayList<>();
            }

            //清空指定会员标签列表
            if (cleanSysTagsList != null && cleanSysTagsList.size() > 0) {
                sysTagsOldList.removeAll(cleanSysTagsList);
            }

            //添加新会员标签
            if (sysTagsList != null && sysTagsList.size() > 0) {
                if (sysTagsOldList.size() == 0) {
                    sysTagsOldList.addAll(sysTagsList);
                } else {
                    //循环遍历，一个个增加,如果类型存在，则删除
                    for (SysTagVo sysTagVo : sysTagsList) {
                        for (int i = sysTagsOldList.size() - 1; i >= 0; i--) {
                            //如果标签类型相等，则删除旧标签
                            if (sysTagsOldList.get(i).getType().intValue() == sysTagVo.getType().intValue()) {
                                sysTagsOldList.remove(i);
                            } else {
                                if (sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE) {
                                    if (sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE) {
                                        sysTagsOldList.remove(i);
                                    }
                                } else if (sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE) {
                                    if (sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE) {
                                        sysTagsOldList.remove(i);
                                    }
                                }
                            }
                        }
                    }
                    sysTagsOldList.addAll(sysTagsList);
                }
            }

            //去重复
            sysTagsOldList = sysTagsOldList.stream().distinct().collect(Collectors.toList());
            wxworkUser.setSysTags(JSONObject.toJSONString(sysTagsOldList));
        }


        //是否修改备注
        Boolean setRemarkFlag = false;
        String userRemark = wxworkUserUpdateDt.getUserRemark();
        if (StringUtils.isNotBlank(userRemark)) {
            //替换变量
            userRemark = userRemark.replaceFirst("\\[昵称\\]", wxworkUser.getNickName());
            wxworkUser.setRemark(Tools.getStr(userRemark));
            setRemarkFlag = true;
        }
        wxworkUserMapper.updateRemarkAndTags(wxworkUser);

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if (setRemarkFlag) {
            //查询机器人
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUser.getDeviceUniqueId(), wxworkUser.getMerId());
            if (deviceWxworkInfo != null) {
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
                msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                msgDto.setMerId(wxworkUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(wxworkUser.getBizUserId());
                setUserRemarkDto.setRemark(Tools.getStr(wxworkUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }

        //计算用户余额并修改
        //变更余额
        Double balance = wxworkUserUpdateDt.getBalance();
        //变更积分
        Integer integral = wxworkUserUpdateDt.getIntegral();
        //积分和余额只要有一个不等于null。表示有变更，则修改
        if (balance != null || integral != null) {

            //发送修改会员数据提醒通知
            StringBuffer content = new StringBuffer("正在修改会员余额和积分;");

            wxworkUser.setUpdateTime(nowTime);
            Double changeBalance = 0.0D;
            //表示修改余额
            if (balance != null) {
                //修改类型类型
                Integer balanceType = wxworkUserUpdateDt.getBalanceType();
                //旧余额
                Double oldBalance = Tools.getDouble(wxworkUser.getBalance());
                //新余额
                Double newBalance = 0.00D;
                if (balanceType.intValue() == -1) { //减量
                    //减少
                    newBalance = Math.sub(oldBalance, balance);
                    changeBalance = Math.sub(0, balance);
                } else if (balanceType.intValue() == 1) { //增量
                    //增加
                    newBalance = Math.add(oldBalance, balance);
                    changeBalance = balance;
                } else {//修改成指定值
                    newBalance = balance;
                    changeBalance = Math.sub(newBalance, oldBalance);
                }
                wxworkUser.setBalance(newBalance);
                content.append("变动余额:" + changeBalance).append(";");
            }

            //变更积分
            Integer changeIntegral = 0;
            if (integral != null) {
                //修改积分类型
                Integer integralType = wxworkUserUpdateDt.getIntegralType();
                //旧积分
                Integer oldIntegral = Tools.getInteger(wxworkUser.getIntegral());
                //新积分
                Integer newIntegral = 0;

                if (integralType.intValue() == -1) { //减量
                    //减少
                    newIntegral = oldIntegral - integral;
                    changeIntegral = 0 - integral;
                } else if (integralType.intValue() == 1) { //增量
                    //增加
                    newIntegral = oldIntegral + integral;
                    changeIntegral = integral;
                } else {//修改成指定值
                    newIntegral = integral;
                    changeIntegral = newIntegral - oldIntegral;
                }

                wxworkUser.setIntegral(newIntegral);
                content.append("变动积分:" + changeIntegral).append(";");
            }
            int j = wxworkUserMapper.updateBalance(wxworkUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
            //增加账号入账明细
            UserAccDetail wxworkUserAccDetail = new UserAccDetail();
            wxworkUserAccDetail.setId(IdWorker.getId());
            wxworkUserAccDetail.setMerId(wxworkUser.getMerId());
            wxworkUserAccDetail.setUserId(wxworkUser.getId());
            wxworkUserAccDetail.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
            wxworkUserAccDetail.setDeviceType(wxworkUser.getDeviceType());
            wxworkUserAccDetail.setChangeInte(changeIntegral);
            wxworkUserAccDetail.setChangeBal(changeBalance);
            wxworkUserAccDetail.setNewBal(wxworkUser.getBalance());
            wxworkUserAccDetail.setNewInte(wxworkUser.getIntegral());
            wxworkUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
            wxworkUserAccDetail.setRemark("运营商人为操作批量修改");
            wxworkUserAccDetail.setCreateTime(nowTime);
            wxworkUserAccDetail.setUpdateTime(nowTime);
            int insert = userAccDetailMapper.insert(wxworkUserAccDetail);
            if (insert != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
            }

            //发送异常报警通知-修改会员敏感信息
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(wxworkUser.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, wxworkUserUpdateDt.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            if (loginVo == null) {
                loginVo = new LoginVo();
            }
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", wxworkUser.getNickName());
            ext.put("wxid", wxworkUser.getBizUserId());
            ext.put("userid", wxworkUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }

        //是否加入黑名单
        if (wxworkUserUpdateDt.getUserBlackType() != null) {
            //查询是否已经在黑名单当中
            //id为merId_wxid
            String id = wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
            Map<String, Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
            WechatBlacklistPrv wechatBlacklistPrv = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
            //不存在，则表示还未加入黑名单，则加入
            if (wechatBlacklistPrv == null) {
                wechatBlacklistPrv = new WechatBlacklistPrv();
                wechatBlacklistPrv.setId(id);
                wechatBlacklistPrv.setMerId(wxworkUser.getMerId());
                wechatBlacklistPrv.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
                wechatBlacklistPrv.setDeviceType(wxworkUser.getDeviceType());
                wechatBlacklistPrv.setWxid(wxworkUser.getBizUserId());
                wechatBlacklistPrv.setNickName(wxworkUser.getNickName());
                wechatBlacklistPrv.setHeadImg(wxworkUser.getHeadImg());
                wechatBlacklistPrv.setType(wxworkUserUpdateDt.getUserBlackType());
                wechatBlacklistPrv.setRemark(wxworkUserUpdateDt.getUserBlackRemark());
                wechatBlacklistPrv.setCreateTime(nowTime);
                wechatBlacklistPrv.setUpdateTime(nowTime);
                elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);
            }

            //添加到全网黑名单
            if (wxworkUserUpdateDt.getAllBackFlag() != null && wxworkUserUpdateDt.getAllBackFlag().intValue() == 1) {
                Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxworkUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if (wechatBlacklistPub == null) {
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(wxworkUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(nowTime);
                    wechatBlacklistPub.setUpdateTime(nowTime);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxworkUser.getBizUserId());
                }
            }
        }

        //是否加入提现黑名单
        if (Tools.getInteger(wxworkUserUpdateDt.getTakeBalBlackFlag()).intValue() == 1) {//开启加入提现黑名单

            //判断会员id是否已经在黑名单当中
            TakeBalBlacklist takeBalBlacklist_old = takeBalBlacklistMapper.selectByUserId(wxworkUserUpdateDt.getId(), wxworkUserUpdateDt.getMerId());
            //不存在，则加入黑名单当中
            if (takeBalBlacklist_old == null) {
                TakeBalBlacklist takeBalBlacklist = new TakeBalBlacklist();
                takeBalBlacklist.setUserId(wxworkUserUpdateDt.getId());
                takeBalBlacklist.setMerId(wxworkUserUpdateDt.getMerId());
                takeBalBlacklist.setNickName(wxworkUser.getNickName());
                takeBalBlacklist.setDeviceType(wxworkUser.getDeviceType());
                takeBalBlacklist.setRemark(wxworkUserUpdateDt.getTakeBalBlackRemark());
                takeBalBlacklist.setAlipayAccount(wxworkUser.getAlipayAccount());
                takeBalBlacklist.setId(IdWorker.getId());
                takeBalBlacklist.setCreateTime(nowTime);
                takeBalBlacklist.setUpdateTime(nowTime);
                //保存加入提现黑名单
                takeBalBlacklistMapper.insert(takeBalBlacklist);
            }
        }

        //营销黑名单
        try {
            marketingRewardsBlackListService.addOrRemoveByFlag(wxworkUser.getMerId(), String.valueOf(wxworkUser.getId()), wxworkUserUpdateDt.getMarketingRewardsBlackListRemark(), wxworkUserUpdateDt.getMarketingRewardsBlackListFlag(),
                    wxworkUserUpdateDt.getSubNotPassFriend());
        } catch (Exception e) {

        }

    }

    /**
     * 单个用户定投筛选
     *
     * @param wxworkUserOptCpcDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void optCpcToOneUser(WxworkUserOptCpcDto wxworkUserOptCpcDto) {

        if (wxworkUserOptCpcDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户id不存在");
        }

        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserOptCpcDto.getId(), wxworkUserOptCpcDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        if (wxworkUserOptCpcDto.getCpaId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定投项目");
        }

        //操作定投筛选功能
        // TODO: 2022/2/24

    }


    /**
     * 更新微信信息
     *
     * @param wxworkUserIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public WxworkUserInfoVo updateUserInfoFromWechat(WxworkUserIdDto wxworkUserIdDto) {

        //返回页面对象
        WxworkUserInfoVo wxworkUserInfoVo = new WxworkUserInfoVo();

        if (wxworkUserIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUserIdDto.getId(), wxworkUserIdDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        if (wxworkUser.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员未绑定机器人信息");
        }

        //从ES中获取个人微信信息
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkUser.getDeviceUniqueId(), wxworkUserIdDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员绑定的机器人不存在或者已经删除");
        }

        if (StringUtils.isNotBlank(deviceWxworkInfo.getDeviceId())) {
            String esId = wxworkUser.getMerId() + "_" + deviceWxworkInfo.getDeviceId() + "_" + wxworkUser.getBizUserId();
            try {

                String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkUserIdDto.getMerId());
                Map<String, Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_contacts, esId, null);
                EsWorkWxContacts esWorkWxContacts = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), EsWorkWxContacts.class);
                if (esWorkWxContacts != null) {
                    //更新微信信息
                    wxworkUser.setNickName(esWorkWxContacts.getUserName());
                    wxworkUser.setHeadImg(esWorkWxContacts.getHimg());
                    wxworkUser.setRemark(esWorkWxContacts.getRemark());
                    wxworkUserMapper.updateById(wxworkUser);
                }
            } catch (Exception e) {
                logger.error("从ES中查询通讯录:error:" + e.getMessage());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新微信信息失败");
            }
        }

        BeanUtils.copyProperties(wxworkUser, wxworkUserInfoVo);
        return wxworkUserInfoVo;
    }

    /**
     * 修改互通的公众号会员的公众号
     *
     * @param wxworkUpdateWxpubUserDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateInterflowWxpubUser(WxworkUpdateWxpubUserDto wxworkUpdateWxpubUserDto) {
        //个人企业微信用户id
        Long id = wxworkUpdateWxpubUserDto.getId();
        //对应新的公众号id
        Long wxpubDeviceUniqueId = wxworkUpdateWxpubUserDto.getWxpubDeviceUniqueId();


        if (id == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人微信id不能为空");
        }

        if (wxpubDeviceUniqueId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新公众号id不能为空");
        }

        WxworkUser wxworkUser = wxworkUserMapper.selectById(id, wxworkUpdateWxpubUserDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        String uzaiUnionId = wxworkUser.getUzaiUnionId();

        if (StringUtils.isBlank(uzaiUnionId)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通公众号");
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectByUzaiUnionId(uzaiUnionId, wxworkUser.getMerId());
        if (wxpubUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通公众号");
        }

//        WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubDeviceUniqueId);
//        if(wxpubInfoEntity == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该公众号不存在或已删除");
//        }

//        wxpubUser.setDeviceUniqueId(wxpubDeviceUniqueId);
//        wxpubUserMapper.updateDevice(wxpubUser);

    }

    /**
     * 修改企业会员订阅信息
     *
     * @param updateSubscribeInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateSubscribeInfo(UpdateSubscribeInfoDto updateSubscribeInfoDto) {
        //企业微信用户id
        Long id = updateSubscribeInfoDto.getId();

        WxworkUser wxworkUser = wxworkUserMapper.selectById(id, updateSubscribeInfoDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        wxworkUser.setSubscribeInfo(updateSubscribeInfoDto.getSubscribeInfo());

        wxworkUserMapper.updateSubscribeInfo(wxworkUser);
    }

    /**
     * 修改会员营销奖励信息
     *
     * @param updateMarketingRewardDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateMarketingReward(UpdateMarketingRewardDto updateMarketingRewardDto) {
        //企业微信用户id
        Long userId = updateMarketingRewardDto.getId();

        WxworkUser wxworkUser = wxworkUserMapper.selectById(userId, updateMarketingRewardDto.getMerId());

        if (wxworkUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }
        //页面修改的营销策略
        MarketingRewardVo marketingReward = updateMarketingRewardDto.getMarketingReward();
        if (marketingReward == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入营销奖励信息");
        }

        //获取该会员的营销策略数据
        String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
        String marketingRewardId = StringUtils.join(wxworkUser.getId(), wxworkUser.getRegSource());
        Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
        MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
        if (marketingRewardVo == null) {
            marketingRewardVo = new MarketingRewardVo();
        }
        marketingRewardVo.setId(marketingRewardId);

        String tradeno_old = StringUtils.join(userId, wxworkUser.getRegSource());
        int now = DateUtil.getNowTime();

        //添加好友奖励
        if (marketingReward.getAddRe() != null) {
            MarketingRewardVo.ReDetail addRe = marketingReward.getAddRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail addReVo = marketingRewardVo.getAddRe();
            if (addReVo == null) {
                addReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(addRe, addReVo, CopyOptions.create().ignoreNullValue());
            addReVo.setUserId(wxworkUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setAddRe(addReVo);

            //奖励状态 0未奖励，1已奖励,
            if (addRe.getStatus() != null && addRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(addRe.getReBal()) > 0 || Tools.getInteger(addRe.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_REGIST.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REGISTER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励下级
        if (marketingReward.getBindRe() != null) {
            MarketingRewardVo.ReDetail bindRe = marketingReward.getBindRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReVo = marketingRewardVo.getBindRe();
            if (bindReVo == null) {
                bindReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindRe, bindReVo, CopyOptions.create().ignoreNullValue());
            bindReVo.setUserId(wxworkUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindRe(bindReVo);

            //奖励状态 0未奖励，1已奖励,
            if (bindRe.getStatus() != null && bindRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(bindRe.getReBal()) > 0 || Tools.getInteger(bindRe.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_INVITE.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励上级
        if (marketingReward.getBindReParent() != null) {
            MarketingRewardVo.ReDetail bindReParent = marketingReward.getBindReParent();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReParentVo = marketingRewardVo.getBindReParent();
            if (bindReParentVo == null) {
                bindReParentVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindReParent, bindReParentVo, CopyOptions.create().ignoreNullValue());
            bindReParentVo.setUserId(wxworkUser.getParentId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindReParent(bindReParentVo);

            //奖励状态 0未奖励，1已奖励,
            if (bindReParent.getStatus() != null && bindReParent.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(bindReParent.getReBal()) > 0 || Tools.getInteger(bindReParent.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引

                    //查询上级会员id
                    Long parentUserId = wxworkUser.getParentId();

                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(parentUserId, AccDetailTypeEnum.REWARD_INVITE_PARENT.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(parentUserId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定代理，奖励代理
        if (marketingReward.getBindReAgent() != null) {
            MarketingRewardVo.ReDetail bindReAgent = marketingReward.getBindReAgent();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReAgentVo = marketingRewardVo.getBindReAgent();
            if (bindReAgentVo == null) {
                bindReAgentVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindReAgent, bindReAgentVo, CopyOptions.create().ignoreNullValue());
            bindReAgentVo.setUserId(wxworkUser.getAgentId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindReAgent(bindReAgentVo);

            //奖励状态 0未奖励，1已奖励,
            if (bindReAgent.getStatus() != null && bindReAgent.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(bindReAgent.getReBal()) > 0 || Tools.getInteger(bindReAgent.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引

                    //查询代理人id
                    Long agentUserId = wxworkUser.getAgentId();

                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(agentUserId, AccDetailTypeEnum.REWARD_ORDER_AGENT.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_AGENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(agentUserId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定合伙人，奖励合伙人
        if (marketingReward.getBindRePartner() != null) {
            MarketingRewardVo.ReDetail bindRePartner = marketingReward.getBindRePartner();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindRePartnerVo = marketingRewardVo.getBindRePartner();
            if (bindRePartnerVo == null) {
                bindRePartnerVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindRePartner, bindRePartnerVo, CopyOptions.create().ignoreNullValue());
            bindRePartnerVo.setUserId(wxworkUser.getPartnerId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindRePartner(bindRePartnerVo);

            //奖励状态 0未奖励，1已奖励,
            if (bindRePartner.getStatus() != null && bindRePartner.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(bindRePartner.getReBal()) > 0 || Tools.getInteger(bindRePartner.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引

                    //查询代理人id
                    Long partnerId = wxworkUser.getPartnerId();

                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(partnerId, AccDetailTypeEnum.REWARD_ORDER_PARTNER.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARTNER.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(partnerId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首查奖励
        if (marketingReward.getFirstQueryRe() != null) {
            MarketingRewardVo.ReDetail firstQueryRe = marketingReward.getFirstQueryRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstQueryReVo = marketingRewardVo.getFirstQueryRe();
            if (firstQueryReVo == null) {
                firstQueryReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstQueryRe, firstQueryReVo, CopyOptions.create().ignoreNullValue());
            firstQueryReVo.setUserId(wxworkUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstQueryRe(firstQueryReVo);

            //奖励状态 0未奖励，1已奖励,
            if (firstQueryRe.getStatus() != null && firstQueryRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(firstQueryRe.getReBal()) > 0 || Tools.getInteger(firstQueryRe.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_QUERY.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_QUERY_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首单奖励
        if (marketingReward.getFirstOrderRe() != null) {
            MarketingRewardVo.ReDetail firstOrderRe = marketingReward.getFirstOrderRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstOrderReVo = marketingRewardVo.getFirstOrderRe();
            if (firstOrderReVo == null) {
                firstOrderReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstOrderRe, firstOrderReVo, CopyOptions.create().ignoreNullValue());
            firstOrderReVo.setUserId(wxworkUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstOrderRe(firstOrderReVo);

            //奖励状态 0未奖励，1已奖励,
            if (firstOrderRe.getStatus() != null && firstOrderRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(firstOrderRe.getReBal()) > 0 || Tools.getInteger(firstOrderRe.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_ORDER.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_ORDER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首次收货奖励
        if (marketingReward.getFirstSettledRe() != null) {
            MarketingRewardVo.ReDetail firstSettledRe = marketingReward.getFirstSettledRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstSettledReVo = marketingRewardVo.getFirstSettledRe();
            if (firstSettledReVo == null) {
                firstSettledReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstSettledRe, firstSettledReVo, CopyOptions.create().ignoreNullValue());
            firstSettledReVo.setUserId(wxworkUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstSettledRe(firstSettledReVo);

            //奖励状态 0未奖励，1已奖励,
            if (firstSettledRe.getStatus() != null && firstSettledRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (Tools.getDouble(firstSettledRe.getReBal()) > 0 || Tools.getInteger(firstSettledRe.getReInte()) > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_SETTLE.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_SETTLED_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxworkUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //修改营销数据ES
        elasticsearchUtil.addDataForObjectSerializer(marketingRewardVo, uzai_marketing_reward_info, tradeno_old);

    }


}
